koichi12 commited on
Commit
13ae937
·
verified ·
1 Parent(s): bdf6bb8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cublas/include/__init__.py +0 -0
  2. tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/CL/cl.h +1578 -0
  3. tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/CL/cl_ext.h +1131 -0
  4. tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/cooperative_groups/details/async.h +452 -0
  5. tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/cooperative_groups/details/coalesced_scan.h +174 -0
  6. tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/cooperative_groups/details/driver_abi.h +99 -0
  7. tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/cooperative_groups/details/sync.h +276 -0
  8. tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/cooperative_groups/scan.h +63 -0
  9. tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/lib/__init__.py +0 -0
  10. tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/lib/libOpenCL.so.1 +0 -0
  11. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/idna/compat.py +13 -0
  12. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/adapters.py +719 -0
  13. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/auth.py +314 -0
  14. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/certs.py +24 -0
  15. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/cookies.py +561 -0
  16. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/exceptions.py +151 -0
  17. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/help.py +127 -0
  18. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/models.py +1037 -0
  19. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/sessions.py +831 -0
  20. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/structures.py +99 -0
  21. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/resolvelib/__pycache__/reporters.cpython-311.pyc +0 -0
  22. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-311.pyc +0 -0
  23. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/_stack.cpython-311.pyc +0 -0
  24. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/_wrap.cpython-311.pyc +0 -0
  25. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/constrain.cpython-311.pyc +0 -0
  26. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/file_proxy.cpython-311.pyc +0 -0
  27. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/filesize.cpython-311.pyc +0 -0
  28. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/layout.cpython-311.pyc +0 -0
  29. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/palette.cpython-311.pyc +0 -0
  30. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/status.cpython-311.pyc +0 -0
  31. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/table.cpython-311.pyc +0 -0
  32. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/traceback.cpython-311.pyc +0 -0
  33. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/tree.cpython-311.pyc +0 -0
  34. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-311.pyc +0 -0
  35. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/contrib/__pycache__/ntlmpool.cpython-311.pyc +0 -0
  36. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/contrib/__pycache__/pyopenssl.cpython-311.pyc +0 -0
  37. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-311.pyc +0 -0
  38. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/__init__.py +49 -0
  39. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/connection.py +149 -0
  40. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/proxy.py +57 -0
  41. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/queue.py +22 -0
  42. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/response.py +107 -0
  43. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/retry.py +622 -0
  44. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/ssl_.py +504 -0
  45. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/url.py +435 -0
  46. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pybind11/_version.py +12 -0
  47. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pybind11/include/pybind11/attr.h +690 -0
  48. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pybind11/include/pybind11/chrono.h +225 -0
  49. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pybind11/include/pybind11/eval.h +156 -0
  50. tuning-competition-baseline/.venv/lib/python3.11/site-packages/pybind11/include/pybind11/operators.h +202 -0
tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cublas/include/__init__.py ADDED
File without changes
tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/CL/cl.h ADDED
@@ -0,0 +1,1578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright (c) 2008-2020 The Khronos Group Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ ******************************************************************************/
16
+
17
+ #ifndef __OPENCL_CL_H
18
+ #define __OPENCL_CL_H
19
+
20
+ #ifdef __APPLE__
21
+ #include <OpenCL/cl_platform.h>
22
+ #else
23
+ #include <CL/cl_platform.h>
24
+ #endif
25
+
26
+ #ifdef __cplusplus
27
+ extern "C" {
28
+ #endif
29
+
30
+ /******************************************************************************/
31
+
32
+ typedef struct _cl_platform_id * cl_platform_id;
33
+ typedef struct _cl_device_id * cl_device_id;
34
+ typedef struct _cl_context * cl_context;
35
+ typedef struct _cl_command_queue * cl_command_queue;
36
+ typedef struct _cl_mem * cl_mem;
37
+ typedef struct _cl_program * cl_program;
38
+ typedef struct _cl_kernel * cl_kernel;
39
+ typedef struct _cl_event * cl_event;
40
+ typedef struct _cl_sampler * cl_sampler;
41
+
42
+ typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */
43
+ typedef cl_ulong cl_bitfield;
44
+ typedef cl_ulong cl_properties;
45
+ typedef cl_bitfield cl_device_type;
46
+ typedef cl_uint cl_platform_info;
47
+ typedef cl_uint cl_device_info;
48
+ typedef cl_bitfield cl_device_fp_config;
49
+ typedef cl_uint cl_device_mem_cache_type;
50
+ typedef cl_uint cl_device_local_mem_type;
51
+ typedef cl_bitfield cl_device_exec_capabilities;
52
+ typedef cl_bitfield cl_device_svm_capabilities;
53
+ typedef cl_bitfield cl_command_queue_properties;
54
+ typedef intptr_t cl_device_partition_property;
55
+ typedef cl_bitfield cl_device_affinity_domain;
56
+
57
+ typedef intptr_t cl_context_properties;
58
+ typedef cl_uint cl_context_info;
59
+ typedef cl_properties cl_queue_properties;
60
+ typedef cl_uint cl_command_queue_info;
61
+ typedef cl_uint cl_channel_order;
62
+ typedef cl_uint cl_channel_type;
63
+ typedef cl_bitfield cl_mem_flags;
64
+ typedef cl_bitfield cl_svm_mem_flags;
65
+ typedef cl_uint cl_mem_object_type;
66
+ typedef cl_uint cl_mem_info;
67
+ typedef cl_bitfield cl_mem_migration_flags;
68
+ typedef cl_uint cl_image_info;
69
+ typedef cl_uint cl_buffer_create_type;
70
+ typedef cl_uint cl_addressing_mode;
71
+ typedef cl_uint cl_filter_mode;
72
+ typedef cl_uint cl_sampler_info;
73
+ typedef cl_bitfield cl_map_flags;
74
+ typedef intptr_t cl_pipe_properties;
75
+ typedef cl_uint cl_pipe_info;
76
+ typedef cl_uint cl_program_info;
77
+ typedef cl_uint cl_program_build_info;
78
+ typedef cl_uint cl_program_binary_type;
79
+ typedef cl_int cl_build_status;
80
+ typedef cl_uint cl_kernel_info;
81
+ typedef cl_uint cl_kernel_arg_info;
82
+ typedef cl_uint cl_kernel_arg_address_qualifier;
83
+ typedef cl_uint cl_kernel_arg_access_qualifier;
84
+ typedef cl_bitfield cl_kernel_arg_type_qualifier;
85
+ typedef cl_uint cl_kernel_work_group_info;
86
+ typedef cl_uint cl_kernel_sub_group_info;
87
+ typedef cl_uint cl_event_info;
88
+ typedef cl_uint cl_command_type;
89
+ typedef cl_uint cl_profiling_info;
90
+ typedef cl_properties cl_sampler_properties;
91
+ typedef cl_uint cl_kernel_exec_info;
92
+ typedef cl_bitfield cl_device_atomic_capabilities;
93
+ typedef cl_bitfield cl_device_device_enqueue_capabilities;
94
+ typedef cl_uint cl_khronos_vendor_id;
95
+ typedef cl_properties cl_mem_properties;
96
+ typedef cl_uint cl_version;
97
+
98
+ typedef struct _cl_image_format {
99
+ cl_channel_order image_channel_order;
100
+ cl_channel_type image_channel_data_type;
101
+ } cl_image_format;
102
+
103
+ typedef struct _cl_image_desc {
104
+ cl_mem_object_type image_type;
105
+ size_t image_width;
106
+ size_t image_height;
107
+ size_t image_depth;
108
+ size_t image_array_size;
109
+ size_t image_row_pitch;
110
+ size_t image_slice_pitch;
111
+ cl_uint num_mip_levels;
112
+ cl_uint num_samples;
113
+ #ifdef __GNUC__
114
+ __extension__ /* Prevents warnings about anonymous union in -pedantic builds */
115
+ #endif
116
+ union {
117
+ cl_mem buffer;
118
+ cl_mem mem_object;
119
+ };
120
+ } cl_image_desc;
121
+
122
+ typedef struct _cl_buffer_region {
123
+ size_t origin;
124
+ size_t size;
125
+ } cl_buffer_region;
126
+
127
+ #define CL_NAME_VERSION_MAX_NAME_SIZE 64
128
+
129
+ typedef struct _cl_name_version {
130
+ cl_version version;
131
+ char name[CL_NAME_VERSION_MAX_NAME_SIZE];
132
+ } cl_name_version;
133
+
134
+ /******************************************************************************/
135
+
136
+ /* Error Codes */
137
+ #define CL_SUCCESS 0
138
+ #define CL_DEVICE_NOT_FOUND -1
139
+ #define CL_DEVICE_NOT_AVAILABLE -2
140
+ #define CL_COMPILER_NOT_AVAILABLE -3
141
+ #define CL_MEM_OBJECT_ALLOCATION_FAILURE -4
142
+ #define CL_OUT_OF_RESOURCES -5
143
+ #define CL_OUT_OF_HOST_MEMORY -6
144
+ #define CL_PROFILING_INFO_NOT_AVAILABLE -7
145
+ #define CL_MEM_COPY_OVERLAP -8
146
+ #define CL_IMAGE_FORMAT_MISMATCH -9
147
+ #define CL_IMAGE_FORMAT_NOT_SUPPORTED -10
148
+ #define CL_BUILD_PROGRAM_FAILURE -11
149
+ #define CL_MAP_FAILURE -12
150
+ #define CL_MISALIGNED_SUB_BUFFER_OFFSET -13
151
+ #define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14
152
+ #define CL_COMPILE_PROGRAM_FAILURE -15
153
+ #define CL_LINKER_NOT_AVAILABLE -16
154
+ #define CL_LINK_PROGRAM_FAILURE -17
155
+ #define CL_DEVICE_PARTITION_FAILED -18
156
+ #define CL_KERNEL_ARG_INFO_NOT_AVAILABLE -19
157
+
158
+ #define CL_INVALID_VALUE -30
159
+ #define CL_INVALID_DEVICE_TYPE -31
160
+ #define CL_INVALID_PLATFORM -32
161
+ #define CL_INVALID_DEVICE -33
162
+ #define CL_INVALID_CONTEXT -34
163
+ #define CL_INVALID_QUEUE_PROPERTIES -35
164
+ #define CL_INVALID_COMMAND_QUEUE -36
165
+ #define CL_INVALID_HOST_PTR -37
166
+ #define CL_INVALID_MEM_OBJECT -38
167
+ #define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39
168
+ #define CL_INVALID_IMAGE_SIZE -40
169
+ #define CL_INVALID_SAMPLER -41
170
+ #define CL_INVALID_BINARY -42
171
+ #define CL_INVALID_BUILD_OPTIONS -43
172
+ #define CL_INVALID_PROGRAM -44
173
+ #define CL_INVALID_PROGRAM_EXECUTABLE -45
174
+ #define CL_INVALID_KERNEL_NAME -46
175
+ #define CL_INVALID_KERNEL_DEFINITION -47
176
+ #define CL_INVALID_KERNEL -48
177
+ #define CL_INVALID_ARG_INDEX -49
178
+ #define CL_INVALID_ARG_VALUE -50
179
+ #define CL_INVALID_ARG_SIZE -51
180
+ #define CL_INVALID_KERNEL_ARGS -52
181
+ #define CL_INVALID_WORK_DIMENSION -53
182
+ #define CL_INVALID_WORK_GROUP_SIZE -54
183
+ #define CL_INVALID_WORK_ITEM_SIZE -55
184
+ #define CL_INVALID_GLOBAL_OFFSET -56
185
+ #define CL_INVALID_EVENT_WAIT_LIST -57
186
+ #define CL_INVALID_EVENT -58
187
+ #define CL_INVALID_OPERATION -59
188
+ #define CL_INVALID_GL_OBJECT -60
189
+ #define CL_INVALID_BUFFER_SIZE -61
190
+ #define CL_INVALID_MIP_LEVEL -62
191
+ #define CL_INVALID_GLOBAL_WORK_SIZE -63
192
+ #define CL_INVALID_PROPERTY -64
193
+ #define CL_INVALID_IMAGE_DESCRIPTOR -65
194
+ #define CL_INVALID_COMPILER_OPTIONS -66
195
+ #define CL_INVALID_LINKER_OPTIONS -67
196
+ #define CL_INVALID_DEVICE_PARTITION_COUNT -68
197
+ #define CL_INVALID_PIPE_SIZE -69
198
+ #define CL_INVALID_DEVICE_QUEUE -70
199
+ #define CL_INVALID_SPEC_ID -71
200
+ #define CL_MAX_SIZE_RESTRICTION_EXCEEDED -72
201
+
202
+ /* OpenCL Version */
203
+ #define CL_VERSION_1_0 1
204
+ #define CL_VERSION_1_1 1
205
+ #define CL_VERSION_1_2 1
206
+ #define CL_VERSION_2_0 1
207
+ #define CL_VERSION_2_1 1
208
+ #define CL_VERSION_2_2 1
209
+ #define CL_VERSION_3_0 1
210
+
211
+ /* cl_bool */
212
+ #define CL_FALSE 0
213
+ #define CL_TRUE 1
214
+ #define CL_BLOCKING CL_TRUE
215
+ #define CL_NON_BLOCKING CL_FALSE
216
+
217
+ /* cl_platform_info */
218
+ #define CL_PLATFORM_PROFILE 0x0900
219
+ #define CL_PLATFORM_VERSION 0x0901
220
+ #define CL_PLATFORM_NAME 0x0902
221
+ #define CL_PLATFORM_VENDOR 0x0903
222
+ #define CL_PLATFORM_EXTENSIONS 0x0904
223
+ #define CL_PLATFORM_HOST_TIMER_RESOLUTION 0x0905
224
+ #define CL_PLATFORM_NUMERIC_VERSION 0x0906
225
+ #define CL_PLATFORM_EXTENSIONS_WITH_VERSION 0x0907
226
+
227
+ /* cl_device_type - bitfield */
228
+ #define CL_DEVICE_TYPE_DEFAULT (1 << 0)
229
+ #define CL_DEVICE_TYPE_CPU (1 << 1)
230
+ #define CL_DEVICE_TYPE_GPU (1 << 2)
231
+ #define CL_DEVICE_TYPE_ACCELERATOR (1 << 3)
232
+ #define CL_DEVICE_TYPE_CUSTOM (1 << 4)
233
+ #define CL_DEVICE_TYPE_ALL 0xFFFFFFFF
234
+
235
+ /* cl_device_info */
236
+ #define CL_DEVICE_TYPE 0x1000
237
+ #define CL_DEVICE_VENDOR_ID 0x1001
238
+ #define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002
239
+ #define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003
240
+ #define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004
241
+ #define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005
242
+ #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006
243
+ #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007
244
+ #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008
245
+ #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009
246
+ #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A
247
+ #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B
248
+ #define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C
249
+ #define CL_DEVICE_ADDRESS_BITS 0x100D
250
+ #define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E
251
+ #define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F
252
+ #define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010
253
+ #define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011
254
+ #define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012
255
+ #define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013
256
+ #define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014
257
+ #define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015
258
+ #define CL_DEVICE_IMAGE_SUPPORT 0x1016
259
+ #define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017
260
+ #define CL_DEVICE_MAX_SAMPLERS 0x1018
261
+ #define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019
262
+ #define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A
263
+ #define CL_DEVICE_SINGLE_FP_CONFIG 0x101B
264
+ #define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C
265
+ #define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D
266
+ #define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E
267
+ #define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F
268
+ #define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020
269
+ #define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021
270
+ #define CL_DEVICE_LOCAL_MEM_TYPE 0x1022
271
+ #define CL_DEVICE_LOCAL_MEM_SIZE 0x1023
272
+ #define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024
273
+ #define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025
274
+ #define CL_DEVICE_ENDIAN_LITTLE 0x1026
275
+ #define CL_DEVICE_AVAILABLE 0x1027
276
+ #define CL_DEVICE_COMPILER_AVAILABLE 0x1028
277
+ #define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029
278
+ #define CL_DEVICE_QUEUE_PROPERTIES 0x102A /* deprecated */
279
+ #define CL_DEVICE_QUEUE_ON_HOST_PROPERTIES 0x102A
280
+ #define CL_DEVICE_NAME 0x102B
281
+ #define CL_DEVICE_VENDOR 0x102C
282
+ #define CL_DRIVER_VERSION 0x102D
283
+ #define CL_DEVICE_PROFILE 0x102E
284
+ #define CL_DEVICE_VERSION 0x102F
285
+ #define CL_DEVICE_EXTENSIONS 0x1030
286
+ #define CL_DEVICE_PLATFORM 0x1031
287
+ #define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032
288
+ /* 0x1033 reserved for CL_DEVICE_HALF_FP_CONFIG which is already defined in "cl_ext.h" */
289
+ #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034
290
+ #define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035 /* deprecated */
291
+ #define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036
292
+ #define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037
293
+ #define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038
294
+ #define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039
295
+ #define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A
296
+ #define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B
297
+ #define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C
298
+ #define CL_DEVICE_OPENCL_C_VERSION 0x103D
299
+ #define CL_DEVICE_LINKER_AVAILABLE 0x103E
300
+ #define CL_DEVICE_BUILT_IN_KERNELS 0x103F
301
+ #define CL_DEVICE_IMAGE_MAX_BUFFER_SIZE 0x1040
302
+ #define CL_DEVICE_IMAGE_MAX_ARRAY_SIZE 0x1041
303
+ #define CL_DEVICE_PARENT_DEVICE 0x1042
304
+ #define CL_DEVICE_PARTITION_MAX_SUB_DEVICES 0x1043
305
+ #define CL_DEVICE_PARTITION_PROPERTIES 0x1044
306
+ #define CL_DEVICE_PARTITION_AFFINITY_DOMAIN 0x1045
307
+ #define CL_DEVICE_PARTITION_TYPE 0x1046
308
+ #define CL_DEVICE_REFERENCE_COUNT 0x1047
309
+ #define CL_DEVICE_PREFERRED_INTEROP_USER_SYNC 0x1048
310
+ #define CL_DEVICE_PRINTF_BUFFER_SIZE 0x1049
311
+ #define CL_DEVICE_IMAGE_PITCH_ALIGNMENT 0x104A
312
+ #define CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT 0x104B
313
+ #define CL_DEVICE_MAX_READ_WRITE_IMAGE_ARGS 0x104C
314
+ #define CL_DEVICE_MAX_GLOBAL_VARIABLE_SIZE 0x104D
315
+ #define CL_DEVICE_QUEUE_ON_DEVICE_PROPERTIES 0x104E
316
+ #define CL_DEVICE_QUEUE_ON_DEVICE_PREFERRED_SIZE 0x104F
317
+ #define CL_DEVICE_QUEUE_ON_DEVICE_MAX_SIZE 0x1050
318
+ #define CL_DEVICE_MAX_ON_DEVICE_QUEUES 0x1051
319
+ #define CL_DEVICE_MAX_ON_DEVICE_EVENTS 0x1052
320
+ #define CL_DEVICE_SVM_CAPABILITIES 0x1053
321
+ #define CL_DEVICE_GLOBAL_VARIABLE_PREFERRED_TOTAL_SIZE 0x1054
322
+ #define CL_DEVICE_MAX_PIPE_ARGS 0x1055
323
+ #define CL_DEVICE_PIPE_MAX_ACTIVE_RESERVATIONS 0x1056
324
+ #define CL_DEVICE_PIPE_MAX_PACKET_SIZE 0x1057
325
+ #define CL_DEVICE_PREFERRED_PLATFORM_ATOMIC_ALIGNMENT 0x1058
326
+ #define CL_DEVICE_PREFERRED_GLOBAL_ATOMIC_ALIGNMENT 0x1059
327
+ #define CL_DEVICE_PREFERRED_LOCAL_ATOMIC_ALIGNMENT 0x105A
328
+ #define CL_DEVICE_IL_VERSION 0x105B
329
+ #define CL_DEVICE_MAX_NUM_SUB_GROUPS 0x105C
330
+ #define CL_DEVICE_SUB_GROUP_INDEPENDENT_FORWARD_PROGRESS 0x105D
331
+ #define CL_DEVICE_NUMERIC_VERSION 0x105E
332
+ #define CL_DEVICE_EXTENSIONS_WITH_VERSION 0x1060
333
+ #define CL_DEVICE_ILS_WITH_VERSION 0x1061
334
+ #define CL_DEVICE_BUILT_IN_KERNELS_WITH_VERSION 0x1062
335
+ #define CL_DEVICE_ATOMIC_MEMORY_CAPABILITIES 0x1063
336
+ #define CL_DEVICE_ATOMIC_FENCE_CAPABILITIES 0x1064
337
+ #define CL_DEVICE_NON_UNIFORM_WORK_GROUP_SUPPORT 0x1065
338
+ #define CL_DEVICE_OPENCL_C_ALL_VERSIONS 0x1066
339
+ #define CL_DEVICE_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x1067
340
+ #define CL_DEVICE_WORK_GROUP_COLLECTIVE_FUNCTIONS_SUPPORT 0x1068
341
+ #define CL_DEVICE_GENERIC_ADDRESS_SPACE_SUPPORT 0x1069
342
+ /* 0x106A to 0x106E - Reserved for upcoming KHR extension */
343
+ #define CL_DEVICE_OPENCL_C_FEATURES 0x106F
344
+ #define CL_DEVICE_DEVICE_ENQUEUE_CAPABILITIES 0x1070
345
+ #define CL_DEVICE_PIPE_SUPPORT 0x1071
346
+ #define CL_DEVICE_LATEST_CONFORMANCE_VERSION_PASSED 0x1072
347
+
348
+ /* cl_device_fp_config - bitfield */
349
+ #define CL_FP_DENORM (1 << 0)
350
+ #define CL_FP_INF_NAN (1 << 1)
351
+ #define CL_FP_ROUND_TO_NEAREST (1 << 2)
352
+ #define CL_FP_ROUND_TO_ZERO (1 << 3)
353
+ #define CL_FP_ROUND_TO_INF (1 << 4)
354
+ #define CL_FP_FMA (1 << 5)
355
+ #define CL_FP_SOFT_FLOAT (1 << 6)
356
+ #define CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT (1 << 7)
357
+
358
+ /* cl_device_mem_cache_type */
359
+ #define CL_NONE 0x0
360
+ #define CL_READ_ONLY_CACHE 0x1
361
+ #define CL_READ_WRITE_CACHE 0x2
362
+
363
+ /* cl_device_local_mem_type */
364
+ #define CL_LOCAL 0x1
365
+ #define CL_GLOBAL 0x2
366
+
367
+ /* cl_device_exec_capabilities - bitfield */
368
+ #define CL_EXEC_KERNEL (1 << 0)
369
+ #define CL_EXEC_NATIVE_KERNEL (1 << 1)
370
+
371
+ /* cl_command_queue_properties - bitfield */
372
+ #define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0)
373
+ #define CL_QUEUE_PROFILING_ENABLE (1 << 1)
374
+ #define CL_QUEUE_ON_DEVICE (1 << 2)
375
+ #define CL_QUEUE_ON_DEVICE_DEFAULT (1 << 3)
376
+
377
+ /* cl_context_info */
378
+ #define CL_CONTEXT_REFERENCE_COUNT 0x1080
379
+ #define CL_CONTEXT_DEVICES 0x1081
380
+ #define CL_CONTEXT_PROPERTIES 0x1082
381
+ #define CL_CONTEXT_NUM_DEVICES 0x1083
382
+
383
+ /* cl_context_properties */
384
+ #define CL_CONTEXT_PLATFORM 0x1084
385
+ #define CL_CONTEXT_INTEROP_USER_SYNC 0x1085
386
+
387
+ /* cl_device_partition_property */
388
+ #define CL_DEVICE_PARTITION_EQUALLY 0x1086
389
+ #define CL_DEVICE_PARTITION_BY_COUNTS 0x1087
390
+ #define CL_DEVICE_PARTITION_BY_COUNTS_LIST_END 0x0
391
+ #define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN 0x1088
392
+
393
+ /* cl_device_affinity_domain */
394
+ #define CL_DEVICE_AFFINITY_DOMAIN_NUMA (1 << 0)
395
+ #define CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE (1 << 1)
396
+ #define CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE (1 << 2)
397
+ #define CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE (1 << 3)
398
+ #define CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE (1 << 4)
399
+ #define CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE (1 << 5)
400
+
401
+ /* cl_device_svm_capabilities */
402
+ #define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER (1 << 0)
403
+ #define CL_DEVICE_SVM_FINE_GRAIN_BUFFER (1 << 1)
404
+ #define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM (1 << 2)
405
+ #define CL_DEVICE_SVM_ATOMICS (1 << 3)
406
+
407
+ /* cl_command_queue_info */
408
+ #define CL_QUEUE_CONTEXT 0x1090
409
+ #define CL_QUEUE_DEVICE 0x1091
410
+ #define CL_QUEUE_REFERENCE_COUNT 0x1092
411
+ #define CL_QUEUE_PROPERTIES 0x1093
412
+ #define CL_QUEUE_SIZE 0x1094
413
+ #define CL_QUEUE_DEVICE_DEFAULT 0x1095
414
+ #define CL_QUEUE_PROPERTIES_ARRAY 0x1098
415
+
416
+ /* cl_mem_flags and cl_svm_mem_flags - bitfield */
417
+ #define CL_MEM_READ_WRITE (1 << 0)
418
+ #define CL_MEM_WRITE_ONLY (1 << 1)
419
+ #define CL_MEM_READ_ONLY (1 << 2)
420
+ #define CL_MEM_USE_HOST_PTR (1 << 3)
421
+ #define CL_MEM_ALLOC_HOST_PTR (1 << 4)
422
+ #define CL_MEM_COPY_HOST_PTR (1 << 5)
423
+ /* reserved (1 << 6) */
424
+ #define CL_MEM_HOST_WRITE_ONLY (1 << 7)
425
+ #define CL_MEM_HOST_READ_ONLY (1 << 8)
426
+ #define CL_MEM_HOST_NO_ACCESS (1 << 9)
427
+ #define CL_MEM_SVM_FINE_GRAIN_BUFFER (1 << 10) /* used by cl_svm_mem_flags only */
428
+ #define CL_MEM_SVM_ATOMICS (1 << 11) /* used by cl_svm_mem_flags only */
429
+ #define CL_MEM_KERNEL_READ_AND_WRITE (1 << 12)
430
+
431
+ /* cl_mem_migration_flags - bitfield */
432
+ #define CL_MIGRATE_MEM_OBJECT_HOST (1 << 0)
433
+ #define CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED (1 << 1)
434
+
435
+ /* cl_channel_order */
436
+ #define CL_R 0x10B0
437
+ #define CL_A 0x10B1
438
+ #define CL_RG 0x10B2
439
+ #define CL_RA 0x10B3
440
+ #define CL_RGB 0x10B4
441
+ #define CL_RGBA 0x10B5
442
+ #define CL_BGRA 0x10B6
443
+ #define CL_ARGB 0x10B7
444
+ #define CL_INTENSITY 0x10B8
445
+ #define CL_LUMINANCE 0x10B9
446
+ #define CL_Rx 0x10BA
447
+ #define CL_RGx 0x10BB
448
+ #define CL_RGBx 0x10BC
449
+ #define CL_DEPTH 0x10BD
450
+ #define CL_DEPTH_STENCIL 0x10BE
451
+ #define CL_sRGB 0x10BF
452
+ #define CL_sRGBx 0x10C0
453
+ #define CL_sRGBA 0x10C1
454
+ #define CL_sBGRA 0x10C2
455
+ #define CL_ABGR 0x10C3
456
+
457
+ /* cl_channel_type */
458
+ #define CL_SNORM_INT8 0x10D0
459
+ #define CL_SNORM_INT16 0x10D1
460
+ #define CL_UNORM_INT8 0x10D2
461
+ #define CL_UNORM_INT16 0x10D3
462
+ #define CL_UNORM_SHORT_565 0x10D4
463
+ #define CL_UNORM_SHORT_555 0x10D5
464
+ #define CL_UNORM_INT_101010 0x10D6
465
+ #define CL_SIGNED_INT8 0x10D7
466
+ #define CL_SIGNED_INT16 0x10D8
467
+ #define CL_SIGNED_INT32 0x10D9
468
+ #define CL_UNSIGNED_INT8 0x10DA
469
+ #define CL_UNSIGNED_INT16 0x10DB
470
+ #define CL_UNSIGNED_INT32 0x10DC
471
+ #define CL_HALF_FLOAT 0x10DD
472
+ #define CL_FLOAT 0x10DE
473
+ #define CL_UNORM_INT24 0x10DF
474
+ #define CL_UNORM_INT_101010_2 0x10E0
475
+
476
+ /* cl_mem_object_type */
477
+ #define CL_MEM_OBJECT_BUFFER 0x10F0
478
+ #define CL_MEM_OBJECT_IMAGE2D 0x10F1
479
+ #define CL_MEM_OBJECT_IMAGE3D 0x10F2
480
+ #define CL_MEM_OBJECT_IMAGE2D_ARRAY 0x10F3
481
+ #define CL_MEM_OBJECT_IMAGE1D 0x10F4
482
+ #define CL_MEM_OBJECT_IMAGE1D_ARRAY 0x10F5
483
+ #define CL_MEM_OBJECT_IMAGE1D_BUFFER 0x10F6
484
+ #define CL_MEM_OBJECT_PIPE 0x10F7
485
+
486
+ /* cl_mem_info */
487
+ #define CL_MEM_TYPE 0x1100
488
+ #define CL_MEM_FLAGS 0x1101
489
+ #define CL_MEM_SIZE 0x1102
490
+ #define CL_MEM_HOST_PTR 0x1103
491
+ #define CL_MEM_MAP_COUNT 0x1104
492
+ #define CL_MEM_REFERENCE_COUNT 0x1105
493
+ #define CL_MEM_CONTEXT 0x1106
494
+ #define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107
495
+ #define CL_MEM_OFFSET 0x1108
496
+ #define CL_MEM_USES_SVM_POINTER 0x1109
497
+ #define CL_MEM_PROPERTIES 0x110A
498
+
499
+ /* cl_image_info */
500
+ #define CL_IMAGE_FORMAT 0x1110
501
+ #define CL_IMAGE_ELEMENT_SIZE 0x1111
502
+ #define CL_IMAGE_ROW_PITCH 0x1112
503
+ #define CL_IMAGE_SLICE_PITCH 0x1113
504
+ #define CL_IMAGE_WIDTH 0x1114
505
+ #define CL_IMAGE_HEIGHT 0x1115
506
+ #define CL_IMAGE_DEPTH 0x1116
507
+ #define CL_IMAGE_ARRAY_SIZE 0x1117
508
+ #define CL_IMAGE_BUFFER 0x1118
509
+ #define CL_IMAGE_NUM_MIP_LEVELS 0x1119
510
+ #define CL_IMAGE_NUM_SAMPLES 0x111A
511
+
512
+ /* cl_pipe_info */
513
+ #define CL_PIPE_PACKET_SIZE 0x1120
514
+ #define CL_PIPE_MAX_PACKETS 0x1121
515
+ #define CL_PIPE_PROPERTIES 0x1122
516
+
517
+ /* cl_addressing_mode */
518
+ #define CL_ADDRESS_NONE 0x1130
519
+ #define CL_ADDRESS_CLAMP_TO_EDGE 0x1131
520
+ #define CL_ADDRESS_CLAMP 0x1132
521
+ #define CL_ADDRESS_REPEAT 0x1133
522
+ #define CL_ADDRESS_MIRRORED_REPEAT 0x1134
523
+
524
+ /* cl_filter_mode */
525
+ #define CL_FILTER_NEAREST 0x1140
526
+ #define CL_FILTER_LINEAR 0x1141
527
+
528
+ /* cl_sampler_info */
529
+ #define CL_SAMPLER_REFERENCE_COUNT 0x1150
530
+ #define CL_SAMPLER_CONTEXT 0x1151
531
+ #define CL_SAMPLER_NORMALIZED_COORDS 0x1152
532
+ #define CL_SAMPLER_ADDRESSING_MODE 0x1153
533
+ #define CL_SAMPLER_FILTER_MODE 0x1154
534
+ /* These enumerants are for the cl_khr_mipmap_image extension.
535
+ They have since been added to cl_ext.h with an appropriate
536
+ KHR suffix, but are left here for backwards compatibility. */
537
+ #define CL_SAMPLER_MIP_FILTER_MODE 0x1155
538
+ #define CL_SAMPLER_LOD_MIN 0x1156
539
+ #define CL_SAMPLER_LOD_MAX 0x1157
540
+ #define CL_SAMPLER_PROPERTIES 0x1158
541
+
542
+ /* cl_map_flags - bitfield */
543
+ #define CL_MAP_READ (1 << 0)
544
+ #define CL_MAP_WRITE (1 << 1)
545
+ #define CL_MAP_WRITE_INVALIDATE_REGION (1 << 2)
546
+
547
+ /* cl_program_info */
548
+ #define CL_PROGRAM_REFERENCE_COUNT 0x1160
549
+ #define CL_PROGRAM_CONTEXT 0x1161
550
+ #define CL_PROGRAM_NUM_DEVICES 0x1162
551
+ #define CL_PROGRAM_DEVICES 0x1163
552
+ #define CL_PROGRAM_SOURCE 0x1164
553
+ #define CL_PROGRAM_BINARY_SIZES 0x1165
554
+ #define CL_PROGRAM_BINARIES 0x1166
555
+ #define CL_PROGRAM_NUM_KERNELS 0x1167
556
+ #define CL_PROGRAM_KERNEL_NAMES 0x1168
557
+ #define CL_PROGRAM_IL 0x1169
558
+ #define CL_PROGRAM_SCOPE_GLOBAL_CTORS_PRESENT 0x116A
559
+ #define CL_PROGRAM_SCOPE_GLOBAL_DTORS_PRESENT 0x116B
560
+
561
+ /* cl_program_build_info */
562
+ #define CL_PROGRAM_BUILD_STATUS 0x1181
563
+ #define CL_PROGRAM_BUILD_OPTIONS 0x1182
564
+ #define CL_PROGRAM_BUILD_LOG 0x1183
565
+ #define CL_PROGRAM_BINARY_TYPE 0x1184
566
+ #define CL_PROGRAM_BUILD_GLOBAL_VARIABLE_TOTAL_SIZE 0x1185
567
+
568
+ /* cl_program_binary_type */
569
+ #define CL_PROGRAM_BINARY_TYPE_NONE 0x0
570
+ #define CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT 0x1
571
+ #define CL_PROGRAM_BINARY_TYPE_LIBRARY 0x2
572
+ #define CL_PROGRAM_BINARY_TYPE_EXECUTABLE 0x4
573
+
574
+ /* cl_build_status */
575
+ #define CL_BUILD_SUCCESS 0
576
+ #define CL_BUILD_NONE -1
577
+ #define CL_BUILD_ERROR -2
578
+ #define CL_BUILD_IN_PROGRESS -3
579
+
580
+ /* cl_kernel_info */
581
+ #define CL_KERNEL_FUNCTION_NAME 0x1190
582
+ #define CL_KERNEL_NUM_ARGS 0x1191
583
+ #define CL_KERNEL_REFERENCE_COUNT 0x1192
584
+ #define CL_KERNEL_CONTEXT 0x1193
585
+ #define CL_KERNEL_PROGRAM 0x1194
586
+ #define CL_KERNEL_ATTRIBUTES 0x1195
587
+
588
+ /* cl_kernel_arg_info */
589
+ #define CL_KERNEL_ARG_ADDRESS_QUALIFIER 0x1196
590
+ #define CL_KERNEL_ARG_ACCESS_QUALIFIER 0x1197
591
+ #define CL_KERNEL_ARG_TYPE_NAME 0x1198
592
+ #define CL_KERNEL_ARG_TYPE_QUALIFIER 0x1199
593
+ #define CL_KERNEL_ARG_NAME 0x119A
594
+
595
+ /* cl_kernel_arg_address_qualifier */
596
+ #define CL_KERNEL_ARG_ADDRESS_GLOBAL 0x119B
597
+ #define CL_KERNEL_ARG_ADDRESS_LOCAL 0x119C
598
+ #define CL_KERNEL_ARG_ADDRESS_CONSTANT 0x119D
599
+ #define CL_KERNEL_ARG_ADDRESS_PRIVATE 0x119E
600
+
601
+ /* cl_kernel_arg_access_qualifier */
602
+ #define CL_KERNEL_ARG_ACCESS_READ_ONLY 0x11A0
603
+ #define CL_KERNEL_ARG_ACCESS_WRITE_ONLY 0x11A1
604
+ #define CL_KERNEL_ARG_ACCESS_READ_WRITE 0x11A2
605
+ #define CL_KERNEL_ARG_ACCESS_NONE 0x11A3
606
+
607
+ /* cl_kernel_arg_type_qualifier */
608
+ #define CL_KERNEL_ARG_TYPE_NONE 0
609
+ #define CL_KERNEL_ARG_TYPE_CONST (1 << 0)
610
+ #define CL_KERNEL_ARG_TYPE_RESTRICT (1 << 1)
611
+ #define CL_KERNEL_ARG_TYPE_VOLATILE (1 << 2)
612
+ #define CL_KERNEL_ARG_TYPE_PIPE (1 << 3)
613
+
614
+ /* cl_kernel_work_group_info */
615
+ #define CL_KERNEL_WORK_GROUP_SIZE 0x11B0
616
+ #define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1
617
+ #define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2
618
+ #define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3
619
+ #define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4
620
+ #define CL_KERNEL_GLOBAL_WORK_SIZE 0x11B5
621
+
622
+ /* cl_kernel_sub_group_info */
623
+ #define CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE 0x2033
624
+ #define CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE 0x2034
625
+ #define CL_KERNEL_LOCAL_SIZE_FOR_SUB_GROUP_COUNT 0x11B8
626
+ #define CL_KERNEL_MAX_NUM_SUB_GROUPS 0x11B9
627
+ #define CL_KERNEL_COMPILE_NUM_SUB_GROUPS 0x11BA
628
+
629
+ /* cl_kernel_exec_info */
630
+ #define CL_KERNEL_EXEC_INFO_SVM_PTRS 0x11B6
631
+ #define CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM 0x11B7
632
+
633
+ /* cl_event_info */
634
+ #define CL_EVENT_COMMAND_QUEUE 0x11D0
635
+ #define CL_EVENT_COMMAND_TYPE 0x11D1
636
+ #define CL_EVENT_REFERENCE_COUNT 0x11D2
637
+ #define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3
638
+ #define CL_EVENT_CONTEXT 0x11D4
639
+
640
+ /* cl_command_type */
641
+ #define CL_COMMAND_NDRANGE_KERNEL 0x11F0
642
+ #define CL_COMMAND_TASK 0x11F1
643
+ #define CL_COMMAND_NATIVE_KERNEL 0x11F2
644
+ #define CL_COMMAND_READ_BUFFER 0x11F3
645
+ #define CL_COMMAND_WRITE_BUFFER 0x11F4
646
+ #define CL_COMMAND_COPY_BUFFER 0x11F5
647
+ #define CL_COMMAND_READ_IMAGE 0x11F6
648
+ #define CL_COMMAND_WRITE_IMAGE 0x11F7
649
+ #define CL_COMMAND_COPY_IMAGE 0x11F8
650
+ #define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9
651
+ #define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA
652
+ #define CL_COMMAND_MAP_BUFFER 0x11FB
653
+ #define CL_COMMAND_MAP_IMAGE 0x11FC
654
+ #define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD
655
+ #define CL_COMMAND_MARKER 0x11FE
656
+ #define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF
657
+ #define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200
658
+ #define CL_COMMAND_READ_BUFFER_RECT 0x1201
659
+ #define CL_COMMAND_WRITE_BUFFER_RECT 0x1202
660
+ #define CL_COMMAND_COPY_BUFFER_RECT 0x1203
661
+ #define CL_COMMAND_USER 0x1204
662
+ #define CL_COMMAND_BARRIER 0x1205
663
+ #define CL_COMMAND_MIGRATE_MEM_OBJECTS 0x1206
664
+ #define CL_COMMAND_FILL_BUFFER 0x1207
665
+ #define CL_COMMAND_FILL_IMAGE 0x1208
666
+ #define CL_COMMAND_SVM_FREE 0x1209
667
+ #define CL_COMMAND_SVM_MEMCPY 0x120A
668
+ #define CL_COMMAND_SVM_MEMFILL 0x120B
669
+ #define CL_COMMAND_SVM_MAP 0x120C
670
+ #define CL_COMMAND_SVM_UNMAP 0x120D
671
+ #define CL_COMMAND_SVM_MIGRATE_MEM 0x120E
672
+
673
+ /* command execution status */
674
+ #define CL_COMPLETE 0x0
675
+ #define CL_RUNNING 0x1
676
+ #define CL_SUBMITTED 0x2
677
+ #define CL_QUEUED 0x3
678
+
679
+ /* cl_buffer_create_type */
680
+ #define CL_BUFFER_CREATE_TYPE_REGION 0x1220
681
+
682
+ /* cl_profiling_info */
683
+ #define CL_PROFILING_COMMAND_QUEUED 0x1280
684
+ #define CL_PROFILING_COMMAND_SUBMIT 0x1281
685
+ #define CL_PROFILING_COMMAND_START 0x1282
686
+ #define CL_PROFILING_COMMAND_END 0x1283
687
+ #define CL_PROFILING_COMMAND_COMPLETE 0x1284
688
+
689
+ /* cl_device_atomic_capabilities - bitfield */
690
+ #define CL_DEVICE_ATOMIC_ORDER_RELAXED (1 << 0)
691
+ #define CL_DEVICE_ATOMIC_ORDER_ACQ_REL (1 << 1)
692
+ #define CL_DEVICE_ATOMIC_ORDER_SEQ_CST (1 << 2)
693
+ #define CL_DEVICE_ATOMIC_SCOPE_WORK_ITEM (1 << 3)
694
+ #define CL_DEVICE_ATOMIC_SCOPE_WORK_GROUP (1 << 4)
695
+ #define CL_DEVICE_ATOMIC_SCOPE_DEVICE (1 << 5)
696
+ #define CL_DEVICE_ATOMIC_SCOPE_ALL_DEVICES (1 << 6)
697
+
698
+ /* cl_device_device_enqueue_capabilities - bitfield */
699
+ #define CL_DEVICE_QUEUE_SUPPORTED (1 << 0)
700
+ #define CL_DEVICE_QUEUE_REPLACEABLE_DEFAULT (1 << 1)
701
+
702
+ /* cl_khronos_vendor_id */
703
+ #define CL_KHRONOS_VENDOR_ID_CODEPLAY 0x10004
704
+
705
+ /* cl_version */
706
+ #define CL_VERSION_MAJOR_BITS (10)
707
+ #define CL_VERSION_MINOR_BITS (10)
708
+ #define CL_VERSION_PATCH_BITS (12)
709
+
710
+ #define CL_VERSION_MAJOR_MASK ((1 << CL_VERSION_MAJOR_BITS) - 1)
711
+ #define CL_VERSION_MINOR_MASK ((1 << CL_VERSION_MINOR_BITS) - 1)
712
+ #define CL_VERSION_PATCH_MASK ((1 << CL_VERSION_PATCH_BITS) - 1)
713
+
714
+ #define CL_VERSION_MAJOR(version) \
715
+ ((version) >> (CL_VERSION_MINOR_BITS + CL_VERSION_PATCH_BITS))
716
+
717
+ #define CL_VERSION_MINOR(version) \
718
+ (((version) >> CL_VERSION_PATCH_BITS) & CL_VERSION_MINOR_MASK)
719
+
720
+ #define CL_VERSION_PATCH(version) ((version) & CL_VERSION_PATCH_MASK)
721
+
722
+ #define CL_MAKE_VERSION(major, minor, patch) \
723
+ ((((major) & CL_VERSION_MAJOR_MASK) \
724
+ << (CL_VERSION_MINOR_BITS + CL_VERSION_PATCH_BITS)) | \
725
+ (((minor) & CL_VERSION_MINOR_MASK) << CL_VERSION_PATCH_BITS) | \
726
+ ((patch) & CL_VERSION_PATCH_MASK))
727
+
728
+ /********************************************************************************************************/
729
+
730
+ /* Platform API */
731
+ extern CL_API_ENTRY cl_int CL_API_CALL
732
+ clGetPlatformIDs(cl_uint num_entries,
733
+ cl_platform_id * platforms,
734
+ cl_uint * num_platforms) CL_API_SUFFIX__VERSION_1_0;
735
+
736
+ extern CL_API_ENTRY cl_int CL_API_CALL
737
+ clGetPlatformInfo(cl_platform_id platform,
738
+ cl_platform_info param_name,
739
+ size_t param_value_size,
740
+ void * param_value,
741
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
742
+
743
+ /* Device APIs */
744
+ extern CL_API_ENTRY cl_int CL_API_CALL
745
+ clGetDeviceIDs(cl_platform_id platform,
746
+ cl_device_type device_type,
747
+ cl_uint num_entries,
748
+ cl_device_id * devices,
749
+ cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_0;
750
+
751
+ extern CL_API_ENTRY cl_int CL_API_CALL
752
+ clGetDeviceInfo(cl_device_id device,
753
+ cl_device_info param_name,
754
+ size_t param_value_size,
755
+ void * param_value,
756
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
757
+
758
+ extern CL_API_ENTRY cl_int CL_API_CALL
759
+ clCreateSubDevices(cl_device_id in_device,
760
+ const cl_device_partition_property * properties,
761
+ cl_uint num_devices,
762
+ cl_device_id * out_devices,
763
+ cl_uint * num_devices_ret) CL_API_SUFFIX__VERSION_1_2;
764
+
765
+ extern CL_API_ENTRY cl_int CL_API_CALL
766
+ clRetainDevice(cl_device_id device) CL_API_SUFFIX__VERSION_1_2;
767
+
768
+ extern CL_API_ENTRY cl_int CL_API_CALL
769
+ clReleaseDevice(cl_device_id device) CL_API_SUFFIX__VERSION_1_2;
770
+
771
+ extern CL_API_ENTRY cl_int CL_API_CALL
772
+ clSetDefaultDeviceCommandQueue(cl_context context,
773
+ cl_device_id device,
774
+ cl_command_queue command_queue) CL_API_SUFFIX__VERSION_2_1;
775
+
776
+ extern CL_API_ENTRY cl_int CL_API_CALL
777
+ clGetDeviceAndHostTimer(cl_device_id device,
778
+ cl_ulong* device_timestamp,
779
+ cl_ulong* host_timestamp) CL_API_SUFFIX__VERSION_2_1;
780
+
781
+ extern CL_API_ENTRY cl_int CL_API_CALL
782
+ clGetHostTimer(cl_device_id device,
783
+ cl_ulong * host_timestamp) CL_API_SUFFIX__VERSION_2_1;
784
+
785
+ /* Context APIs */
786
+ extern CL_API_ENTRY cl_context CL_API_CALL
787
+ clCreateContext(const cl_context_properties * properties,
788
+ cl_uint num_devices,
789
+ const cl_device_id * devices,
790
+ void (CL_CALLBACK * pfn_notify)(const char * errinfo,
791
+ const void * private_info,
792
+ size_t cb,
793
+ void * user_data),
794
+ void * user_data,
795
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
796
+
797
+ extern CL_API_ENTRY cl_context CL_API_CALL
798
+ clCreateContextFromType(const cl_context_properties * properties,
799
+ cl_device_type device_type,
800
+ void (CL_CALLBACK * pfn_notify)(const char * errinfo,
801
+ const void * private_info,
802
+ size_t cb,
803
+ void * user_data),
804
+ void * user_data,
805
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
806
+
807
+ extern CL_API_ENTRY cl_int CL_API_CALL
808
+ clRetainContext(cl_context context) CL_API_SUFFIX__VERSION_1_0;
809
+
810
+ extern CL_API_ENTRY cl_int CL_API_CALL
811
+ clReleaseContext(cl_context context) CL_API_SUFFIX__VERSION_1_0;
812
+
813
+ extern CL_API_ENTRY cl_int CL_API_CALL
814
+ clGetContextInfo(cl_context context,
815
+ cl_context_info param_name,
816
+ size_t param_value_size,
817
+ void * param_value,
818
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
819
+
820
+ extern CL_API_ENTRY cl_int CL_API_CALL
821
+ clSetContextDestructorCallback(cl_context context,
822
+ void (CL_CALLBACK* pfn_notify)(cl_context context,
823
+ void* user_data),
824
+ void* user_data) CL_API_SUFFIX__VERSION_3_0;
825
+
826
+ extern CL_API_ENTRY cl_int CL_API_CALL
827
+ clEnqueueTask(cl_command_queue command_queue,
828
+ cl_kernel kernel,
829
+ cl_uint num_events_in_wait_list,
830
+ const cl_event * event_wait_list,
831
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
832
+
833
+ /* Command Queue APIs */
834
+ extern CL_API_ENTRY cl_command_queue CL_API_CALL
835
+ clCreateCommandQueue(cl_context context,
836
+ cl_device_id device,
837
+ cl_command_queue_properties properties,
838
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
839
+
840
+ extern CL_API_ENTRY cl_command_queue CL_API_CALL
841
+ clCreateCommandQueueWithProperties(cl_context context,
842
+ cl_device_id device,
843
+ const cl_queue_properties * properties,
844
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_2_0;
845
+
846
+ extern CL_API_ENTRY cl_int CL_API_CALL
847
+ clRetainCommandQueue(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0;
848
+
849
+ extern CL_API_ENTRY cl_int CL_API_CALL
850
+ clReleaseCommandQueue(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0;
851
+
852
+ extern CL_API_ENTRY cl_int CL_API_CALL
853
+ clGetCommandQueueInfo(cl_command_queue command_queue,
854
+ cl_command_queue_info param_name,
855
+ size_t param_value_size,
856
+ void * param_value,
857
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
858
+
859
+ /* Memory Object APIs */
860
+ extern CL_API_ENTRY cl_mem CL_API_CALL
861
+ clCreateBuffer(cl_context context,
862
+ cl_mem_flags flags,
863
+ size_t size,
864
+ void * host_ptr,
865
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
866
+
867
+ extern CL_API_ENTRY cl_mem CL_API_CALL
868
+ clCreateSubBuffer(cl_mem buffer,
869
+ cl_mem_flags flags,
870
+ cl_buffer_create_type buffer_create_type,
871
+ const void * buffer_create_info,
872
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_1;
873
+
874
+ extern CL_API_ENTRY cl_mem CL_API_CALL
875
+ clCreateImage(cl_context context,
876
+ cl_mem_flags flags,
877
+ const cl_image_format * image_format,
878
+ const cl_image_desc * image_desc,
879
+ void * host_ptr,
880
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2;
881
+
882
+ extern CL_API_ENTRY cl_mem CL_API_CALL
883
+ clCreatePipe(cl_context context,
884
+ cl_mem_flags flags,
885
+ cl_uint pipe_packet_size,
886
+ cl_uint pipe_max_packets,
887
+ const cl_pipe_properties * properties,
888
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_2_0;
889
+
890
+ extern CL_API_ENTRY cl_mem CL_API_CALL
891
+ clCreateBufferWithProperties(cl_context context,
892
+ const cl_mem_properties * properties,
893
+ cl_mem_flags flags,
894
+ size_t size,
895
+ void * host_ptr,
896
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_3_0;
897
+
898
+ extern CL_API_ENTRY cl_mem CL_API_CALL
899
+ clCreateImageWithProperties(cl_context context,
900
+ const cl_mem_properties * properties,
901
+ cl_mem_flags flags,
902
+ const cl_image_format * image_format,
903
+ const cl_image_desc * image_desc,
904
+ void * host_ptr,
905
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_3_0;
906
+
907
+ extern CL_API_ENTRY cl_int CL_API_CALL
908
+ clRetainMemObject(cl_mem memobj) CL_API_SUFFIX__VERSION_1_0;
909
+
910
+ extern CL_API_ENTRY cl_int CL_API_CALL
911
+ clReleaseMemObject(cl_mem memobj) CL_API_SUFFIX__VERSION_1_0;
912
+
913
+ extern CL_API_ENTRY cl_int CL_API_CALL
914
+ clGetSupportedImageFormats(cl_context context,
915
+ cl_mem_flags flags,
916
+ cl_mem_object_type image_type,
917
+ cl_uint num_entries,
918
+ cl_image_format * image_formats,
919
+ cl_uint * num_image_formats) CL_API_SUFFIX__VERSION_1_0;
920
+
921
+ extern CL_API_ENTRY cl_int CL_API_CALL
922
+ clGetMemObjectInfo(cl_mem memobj,
923
+ cl_mem_info param_name,
924
+ size_t param_value_size,
925
+ void * param_value,
926
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
927
+
928
+ extern CL_API_ENTRY cl_int CL_API_CALL
929
+ clGetImageInfo(cl_mem image,
930
+ cl_image_info param_name,
931
+ size_t param_value_size,
932
+ void * param_value,
933
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
934
+
935
+ extern CL_API_ENTRY cl_int CL_API_CALL
936
+ clGetPipeInfo(cl_mem pipe,
937
+ cl_pipe_info param_name,
938
+ size_t param_value_size,
939
+ void * param_value,
940
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_2_0;
941
+
942
+ extern CL_API_ENTRY cl_int CL_API_CALL
943
+ clSetMemObjectDestructorCallback(cl_mem memobj,
944
+ void (CL_CALLBACK * pfn_notify)(cl_mem memobj,
945
+ void * user_data),
946
+ void * user_data) CL_API_SUFFIX__VERSION_1_1;
947
+
948
+ /* SVM Allocation APIs */
949
+ extern CL_API_ENTRY void * CL_API_CALL
950
+ clSVMAlloc(cl_context context,
951
+ cl_svm_mem_flags flags,
952
+ size_t size,
953
+ cl_uint alignment) CL_API_SUFFIX__VERSION_2_0;
954
+
955
+ extern CL_API_ENTRY void CL_API_CALL
956
+ clSVMFree(cl_context context,
957
+ void * svm_pointer) CL_API_SUFFIX__VERSION_2_0;
958
+
959
+ /* Sampler APIs */
960
+ extern CL_API_ENTRY cl_sampler CL_API_CALL
961
+ clCreateSampler(cl_context context,
962
+ cl_bool normalized_coords,
963
+ cl_addressing_mode addressing_mode,
964
+ cl_filter_mode filter_mode,
965
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
966
+
967
+ extern CL_API_ENTRY cl_sampler CL_API_CALL
968
+ clCreateSamplerWithProperties(cl_context context,
969
+ const cl_sampler_properties * sampler_properties,
970
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_2_0;
971
+
972
+ extern CL_API_ENTRY cl_int CL_API_CALL
973
+ clRetainSampler(cl_sampler sampler) CL_API_SUFFIX__VERSION_1_0;
974
+
975
+ extern CL_API_ENTRY cl_int CL_API_CALL
976
+ clReleaseSampler(cl_sampler sampler) CL_API_SUFFIX__VERSION_1_0;
977
+
978
+ extern CL_API_ENTRY cl_int CL_API_CALL
979
+ clGetSamplerInfo(cl_sampler sampler,
980
+ cl_sampler_info param_name,
981
+ size_t param_value_size,
982
+ void * param_value,
983
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
984
+
985
+ /* Program Object APIs */
986
+ extern CL_API_ENTRY cl_program CL_API_CALL
987
+ clCreateProgramWithSource(cl_context context,
988
+ cl_uint count,
989
+ const char ** strings,
990
+ const size_t * lengths,
991
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
992
+
993
+ extern CL_API_ENTRY cl_program CL_API_CALL
994
+ clCreateProgramWithBinary(cl_context context,
995
+ cl_uint num_devices,
996
+ const cl_device_id * device_list,
997
+ const size_t * lengths,
998
+ const unsigned char ** binaries,
999
+ cl_int * binary_status,
1000
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
1001
+
1002
+ extern CL_API_ENTRY cl_program CL_API_CALL
1003
+ clCreateProgramWithBuiltInKernels(cl_context context,
1004
+ cl_uint num_devices,
1005
+ const cl_device_id * device_list,
1006
+ const char * kernel_names,
1007
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2;
1008
+
1009
+ extern CL_API_ENTRY cl_program CL_API_CALL
1010
+ clCreateProgramWithIL(cl_context context,
1011
+ const void* il,
1012
+ size_t length,
1013
+ cl_int* errcode_ret) CL_API_SUFFIX__VERSION_2_1;
1014
+
1015
+ extern CL_API_ENTRY cl_int CL_API_CALL
1016
+ clRetainProgram(cl_program program) CL_API_SUFFIX__VERSION_1_0;
1017
+
1018
+ extern CL_API_ENTRY cl_int CL_API_CALL
1019
+ clReleaseProgram(cl_program program) CL_API_SUFFIX__VERSION_1_0;
1020
+
1021
+ extern CL_API_ENTRY cl_int CL_API_CALL
1022
+ clBuildProgram(cl_program program,
1023
+ cl_uint num_devices,
1024
+ const cl_device_id * device_list,
1025
+ const char * options,
1026
+ void (CL_CALLBACK * pfn_notify)(cl_program program,
1027
+ void * user_data),
1028
+ void * user_data) CL_API_SUFFIX__VERSION_1_0;
1029
+
1030
+ extern CL_API_ENTRY cl_int CL_API_CALL
1031
+ clCompileProgram(cl_program program,
1032
+ cl_uint num_devices,
1033
+ const cl_device_id * device_list,
1034
+ const char * options,
1035
+ cl_uint num_input_headers,
1036
+ const cl_program * input_headers,
1037
+ const char ** header_include_names,
1038
+ void (CL_CALLBACK * pfn_notify)(cl_program program,
1039
+ void * user_data),
1040
+ void * user_data) CL_API_SUFFIX__VERSION_1_2;
1041
+
1042
+ extern CL_API_ENTRY cl_program CL_API_CALL
1043
+ clLinkProgram(cl_context context,
1044
+ cl_uint num_devices,
1045
+ const cl_device_id * device_list,
1046
+ const char * options,
1047
+ cl_uint num_input_programs,
1048
+ const cl_program * input_programs,
1049
+ void (CL_CALLBACK * pfn_notify)(cl_program program,
1050
+ void * user_data),
1051
+ void * user_data,
1052
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_2;
1053
+
1054
+ extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_2_2_DEPRECATED cl_int CL_API_CALL
1055
+ clSetProgramReleaseCallback(cl_program program,
1056
+ void (CL_CALLBACK * pfn_notify)(cl_program program,
1057
+ void * user_data),
1058
+ void * user_data) CL_EXT_SUFFIX__VERSION_2_2_DEPRECATED;
1059
+
1060
+ extern CL_API_ENTRY cl_int CL_API_CALL
1061
+ clSetProgramSpecializationConstant(cl_program program,
1062
+ cl_uint spec_id,
1063
+ size_t spec_size,
1064
+ const void* spec_value) CL_API_SUFFIX__VERSION_2_2;
1065
+
1066
+ extern CL_API_ENTRY cl_int CL_API_CALL
1067
+ clUnloadPlatformCompiler(cl_platform_id platform) CL_API_SUFFIX__VERSION_1_2;
1068
+
1069
+ extern CL_API_ENTRY cl_int CL_API_CALL
1070
+ clGetProgramInfo(cl_program program,
1071
+ cl_program_info param_name,
1072
+ size_t param_value_size,
1073
+ void * param_value,
1074
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
1075
+
1076
+ extern CL_API_ENTRY cl_int CL_API_CALL
1077
+ clGetProgramBuildInfo(cl_program program,
1078
+ cl_device_id device,
1079
+ cl_program_build_info param_name,
1080
+ size_t param_value_size,
1081
+ void * param_value,
1082
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
1083
+
1084
+ /* Kernel Object APIs */
1085
+ extern CL_API_ENTRY cl_kernel CL_API_CALL
1086
+ clCreateKernel(cl_program program,
1087
+ const char * kernel_name,
1088
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
1089
+
1090
+ extern CL_API_ENTRY cl_int CL_API_CALL
1091
+ clCreateKernelsInProgram(cl_program program,
1092
+ cl_uint num_kernels,
1093
+ cl_kernel * kernels,
1094
+ cl_uint * num_kernels_ret) CL_API_SUFFIX__VERSION_1_0;
1095
+
1096
+ extern CL_API_ENTRY cl_kernel CL_API_CALL
1097
+ clCloneKernel(cl_kernel source_kernel,
1098
+ cl_int* errcode_ret) CL_API_SUFFIX__VERSION_2_1;
1099
+
1100
+ extern CL_API_ENTRY cl_int CL_API_CALL
1101
+ clRetainKernel(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_0;
1102
+
1103
+ extern CL_API_ENTRY cl_int CL_API_CALL
1104
+ clReleaseKernel(cl_kernel kernel) CL_API_SUFFIX__VERSION_1_0;
1105
+
1106
+ extern CL_API_ENTRY cl_int CL_API_CALL
1107
+ clSetKernelArg(cl_kernel kernel,
1108
+ cl_uint arg_index,
1109
+ size_t arg_size,
1110
+ const void * arg_value) CL_API_SUFFIX__VERSION_1_0;
1111
+
1112
+ extern CL_API_ENTRY cl_int CL_API_CALL
1113
+ clSetKernelArgSVMPointer(cl_kernel kernel,
1114
+ cl_uint arg_index,
1115
+ const void * arg_value) CL_API_SUFFIX__VERSION_2_0;
1116
+
1117
+ extern CL_API_ENTRY cl_int CL_API_CALL
1118
+ clSetKernelExecInfo(cl_kernel kernel,
1119
+ cl_kernel_exec_info param_name,
1120
+ size_t param_value_size,
1121
+ const void * param_value) CL_API_SUFFIX__VERSION_2_0;
1122
+
1123
+ extern CL_API_ENTRY cl_int CL_API_CALL
1124
+ clGetKernelInfo(cl_kernel kernel,
1125
+ cl_kernel_info param_name,
1126
+ size_t param_value_size,
1127
+ void * param_value,
1128
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
1129
+
1130
+ extern CL_API_ENTRY cl_int CL_API_CALL
1131
+ clGetKernelArgInfo(cl_kernel kernel,
1132
+ cl_uint arg_indx,
1133
+ cl_kernel_arg_info param_name,
1134
+ size_t param_value_size,
1135
+ void * param_value,
1136
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_2;
1137
+
1138
+ extern CL_API_ENTRY cl_int CL_API_CALL
1139
+ clGetKernelWorkGroupInfo(cl_kernel kernel,
1140
+ cl_device_id device,
1141
+ cl_kernel_work_group_info param_name,
1142
+ size_t param_value_size,
1143
+ void * param_value,
1144
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
1145
+
1146
+ extern CL_API_ENTRY cl_int CL_API_CALL
1147
+ clGetKernelSubGroupInfo(cl_kernel kernel,
1148
+ cl_device_id device,
1149
+ cl_kernel_sub_group_info param_name,
1150
+ size_t input_value_size,
1151
+ const void* input_value,
1152
+ size_t param_value_size,
1153
+ void* param_value,
1154
+ size_t* param_value_size_ret) CL_API_SUFFIX__VERSION_2_1;
1155
+
1156
+ /* Event Object APIs */
1157
+ extern CL_API_ENTRY cl_int CL_API_CALL
1158
+ clWaitForEvents(cl_uint num_events,
1159
+ const cl_event * event_list) CL_API_SUFFIX__VERSION_1_0;
1160
+
1161
+ extern CL_API_ENTRY cl_int CL_API_CALL
1162
+ clGetEventInfo(cl_event event,
1163
+ cl_event_info param_name,
1164
+ size_t param_value_size,
1165
+ void * param_value,
1166
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
1167
+
1168
+ extern CL_API_ENTRY cl_event CL_API_CALL
1169
+ clCreateUserEvent(cl_context context,
1170
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_1;
1171
+
1172
+ extern CL_API_ENTRY cl_int CL_API_CALL
1173
+ clRetainEvent(cl_event event) CL_API_SUFFIX__VERSION_1_0;
1174
+
1175
+ extern CL_API_ENTRY cl_int CL_API_CALL
1176
+ clReleaseEvent(cl_event event) CL_API_SUFFIX__VERSION_1_0;
1177
+
1178
+ extern CL_API_ENTRY cl_int CL_API_CALL
1179
+ clSetUserEventStatus(cl_event event,
1180
+ cl_int execution_status) CL_API_SUFFIX__VERSION_1_1;
1181
+
1182
+ extern CL_API_ENTRY cl_int CL_API_CALL
1183
+ clSetEventCallback(cl_event event,
1184
+ cl_int command_exec_callback_type,
1185
+ void (CL_CALLBACK * pfn_notify)(cl_event event,
1186
+ cl_int event_command_status,
1187
+ void * user_data),
1188
+ void * user_data) CL_API_SUFFIX__VERSION_1_1;
1189
+
1190
+ /* Profiling APIs */
1191
+ extern CL_API_ENTRY cl_int CL_API_CALL
1192
+ clGetEventProfilingInfo(cl_event event,
1193
+ cl_profiling_info param_name,
1194
+ size_t param_value_size,
1195
+ void * param_value,
1196
+ size_t * param_value_size_ret) CL_API_SUFFIX__VERSION_1_0;
1197
+
1198
+ /* Flush and Finish APIs */
1199
+ extern CL_API_ENTRY cl_int CL_API_CALL
1200
+ clFlush(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0;
1201
+
1202
+ extern CL_API_ENTRY cl_int CL_API_CALL
1203
+ clFinish(cl_command_queue command_queue) CL_API_SUFFIX__VERSION_1_0;
1204
+
1205
+ /* Enqueued Commands APIs */
1206
+ extern CL_API_ENTRY cl_int CL_API_CALL
1207
+ clEnqueueReadBuffer(cl_command_queue command_queue,
1208
+ cl_mem buffer,
1209
+ cl_bool blocking_read,
1210
+ size_t offset,
1211
+ size_t size,
1212
+ void * ptr,
1213
+ cl_uint num_events_in_wait_list,
1214
+ const cl_event * event_wait_list,
1215
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1216
+
1217
+ extern CL_API_ENTRY cl_int CL_API_CALL
1218
+ clEnqueueReadBufferRect(cl_command_queue command_queue,
1219
+ cl_mem buffer,
1220
+ cl_bool blocking_read,
1221
+ const size_t * buffer_offset,
1222
+ const size_t * host_offset,
1223
+ const size_t * region,
1224
+ size_t buffer_row_pitch,
1225
+ size_t buffer_slice_pitch,
1226
+ size_t host_row_pitch,
1227
+ size_t host_slice_pitch,
1228
+ void * ptr,
1229
+ cl_uint num_events_in_wait_list,
1230
+ const cl_event * event_wait_list,
1231
+ cl_event * event) CL_API_SUFFIX__VERSION_1_1;
1232
+
1233
+ extern CL_API_ENTRY cl_int CL_API_CALL
1234
+ clEnqueueWriteBuffer(cl_command_queue command_queue,
1235
+ cl_mem buffer,
1236
+ cl_bool blocking_write,
1237
+ size_t offset,
1238
+ size_t size,
1239
+ const void * ptr,
1240
+ cl_uint num_events_in_wait_list,
1241
+ const cl_event * event_wait_list,
1242
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1243
+
1244
+ extern CL_API_ENTRY cl_int CL_API_CALL
1245
+ clEnqueueWriteBufferRect(cl_command_queue command_queue,
1246
+ cl_mem buffer,
1247
+ cl_bool blocking_write,
1248
+ const size_t * buffer_offset,
1249
+ const size_t * host_offset,
1250
+ const size_t * region,
1251
+ size_t buffer_row_pitch,
1252
+ size_t buffer_slice_pitch,
1253
+ size_t host_row_pitch,
1254
+ size_t host_slice_pitch,
1255
+ const void * ptr,
1256
+ cl_uint num_events_in_wait_list,
1257
+ const cl_event * event_wait_list,
1258
+ cl_event * event) CL_API_SUFFIX__VERSION_1_1;
1259
+
1260
+ extern CL_API_ENTRY cl_int CL_API_CALL
1261
+ clEnqueueFillBuffer(cl_command_queue command_queue,
1262
+ cl_mem buffer,
1263
+ const void * pattern,
1264
+ size_t pattern_size,
1265
+ size_t offset,
1266
+ size_t size,
1267
+ cl_uint num_events_in_wait_list,
1268
+ const cl_event * event_wait_list,
1269
+ cl_event * event) CL_API_SUFFIX__VERSION_1_2;
1270
+
1271
+ extern CL_API_ENTRY cl_int CL_API_CALL
1272
+ clEnqueueCopyBuffer(cl_command_queue command_queue,
1273
+ cl_mem src_buffer,
1274
+ cl_mem dst_buffer,
1275
+ size_t src_offset,
1276
+ size_t dst_offset,
1277
+ size_t size,
1278
+ cl_uint num_events_in_wait_list,
1279
+ const cl_event * event_wait_list,
1280
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1281
+
1282
+ extern CL_API_ENTRY cl_int CL_API_CALL
1283
+ clEnqueueCopyBufferRect(cl_command_queue command_queue,
1284
+ cl_mem src_buffer,
1285
+ cl_mem dst_buffer,
1286
+ const size_t * src_origin,
1287
+ const size_t * dst_origin,
1288
+ const size_t * region,
1289
+ size_t src_row_pitch,
1290
+ size_t src_slice_pitch,
1291
+ size_t dst_row_pitch,
1292
+ size_t dst_slice_pitch,
1293
+ cl_uint num_events_in_wait_list,
1294
+ const cl_event * event_wait_list,
1295
+ cl_event * event) CL_API_SUFFIX__VERSION_1_1;
1296
+
1297
+ extern CL_API_ENTRY cl_int CL_API_CALL
1298
+ clEnqueueReadImage(cl_command_queue command_queue,
1299
+ cl_mem image,
1300
+ cl_bool blocking_read,
1301
+ const size_t * origin,
1302
+ const size_t * region,
1303
+ size_t row_pitch,
1304
+ size_t slice_pitch,
1305
+ void * ptr,
1306
+ cl_uint num_events_in_wait_list,
1307
+ const cl_event * event_wait_list,
1308
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1309
+
1310
+ extern CL_API_ENTRY cl_int CL_API_CALL
1311
+ clEnqueueWriteImage(cl_command_queue command_queue,
1312
+ cl_mem image,
1313
+ cl_bool blocking_write,
1314
+ const size_t * origin,
1315
+ const size_t * region,
1316
+ size_t input_row_pitch,
1317
+ size_t input_slice_pitch,
1318
+ const void * ptr,
1319
+ cl_uint num_events_in_wait_list,
1320
+ const cl_event * event_wait_list,
1321
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1322
+
1323
+ extern CL_API_ENTRY cl_int CL_API_CALL
1324
+ clEnqueueFillImage(cl_command_queue command_queue,
1325
+ cl_mem image,
1326
+ const void * fill_color,
1327
+ const size_t * origin,
1328
+ const size_t * region,
1329
+ cl_uint num_events_in_wait_list,
1330
+ const cl_event * event_wait_list,
1331
+ cl_event * event) CL_API_SUFFIX__VERSION_1_2;
1332
+
1333
+ extern CL_API_ENTRY cl_int CL_API_CALL
1334
+ clEnqueueCopyImage(cl_command_queue command_queue,
1335
+ cl_mem src_image,
1336
+ cl_mem dst_image,
1337
+ const size_t * src_origin,
1338
+ const size_t * dst_origin,
1339
+ const size_t * region,
1340
+ cl_uint num_events_in_wait_list,
1341
+ const cl_event * event_wait_list,
1342
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1343
+
1344
+ extern CL_API_ENTRY cl_int CL_API_CALL
1345
+ clEnqueueCopyImageToBuffer(cl_command_queue command_queue,
1346
+ cl_mem src_image,
1347
+ cl_mem dst_buffer,
1348
+ const size_t * src_origin,
1349
+ const size_t * region,
1350
+ size_t dst_offset,
1351
+ cl_uint num_events_in_wait_list,
1352
+ const cl_event * event_wait_list,
1353
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1354
+
1355
+ extern CL_API_ENTRY cl_int CL_API_CALL
1356
+ clEnqueueCopyBufferToImage(cl_command_queue command_queue,
1357
+ cl_mem src_buffer,
1358
+ cl_mem dst_image,
1359
+ size_t src_offset,
1360
+ const size_t * dst_origin,
1361
+ const size_t * region,
1362
+ cl_uint num_events_in_wait_list,
1363
+ const cl_event * event_wait_list,
1364
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1365
+
1366
+ extern CL_API_ENTRY void * CL_API_CALL
1367
+ clEnqueueMapBuffer(cl_command_queue command_queue,
1368
+ cl_mem buffer,
1369
+ cl_bool blocking_map,
1370
+ cl_map_flags map_flags,
1371
+ size_t offset,
1372
+ size_t size,
1373
+ cl_uint num_events_in_wait_list,
1374
+ const cl_event * event_wait_list,
1375
+ cl_event * event,
1376
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
1377
+
1378
+ extern CL_API_ENTRY void * CL_API_CALL
1379
+ clEnqueueMapImage(cl_command_queue command_queue,
1380
+ cl_mem image,
1381
+ cl_bool blocking_map,
1382
+ cl_map_flags map_flags,
1383
+ const size_t * origin,
1384
+ const size_t * region,
1385
+ size_t * image_row_pitch,
1386
+ size_t * image_slice_pitch,
1387
+ cl_uint num_events_in_wait_list,
1388
+ const cl_event * event_wait_list,
1389
+ cl_event * event,
1390
+ cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
1391
+
1392
+ extern CL_API_ENTRY cl_int CL_API_CALL
1393
+ clEnqueueUnmapMemObject(cl_command_queue command_queue,
1394
+ cl_mem memobj,
1395
+ void * mapped_ptr,
1396
+ cl_uint num_events_in_wait_list,
1397
+ const cl_event * event_wait_list,
1398
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1399
+
1400
+ extern CL_API_ENTRY cl_int CL_API_CALL
1401
+ clEnqueueMigrateMemObjects(cl_command_queue command_queue,
1402
+ cl_uint num_mem_objects,
1403
+ const cl_mem * mem_objects,
1404
+ cl_mem_migration_flags flags,
1405
+ cl_uint num_events_in_wait_list,
1406
+ const cl_event * event_wait_list,
1407
+ cl_event * event) CL_API_SUFFIX__VERSION_1_2;
1408
+
1409
+ extern CL_API_ENTRY cl_int CL_API_CALL
1410
+ clEnqueueNDRangeKernel(cl_command_queue command_queue,
1411
+ cl_kernel kernel,
1412
+ cl_uint work_dim,
1413
+ const size_t * global_work_offset,
1414
+ const size_t * global_work_size,
1415
+ const size_t * local_work_size,
1416
+ cl_uint num_events_in_wait_list,
1417
+ const cl_event * event_wait_list,
1418
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1419
+
1420
+ extern CL_API_ENTRY cl_int CL_API_CALL
1421
+ clEnqueueNativeKernel(cl_command_queue command_queue,
1422
+ void (CL_CALLBACK * user_func)(void *),
1423
+ void * args,
1424
+ size_t cb_args,
1425
+ cl_uint num_mem_objects,
1426
+ const cl_mem * mem_list,
1427
+ const void ** args_mem_loc,
1428
+ cl_uint num_events_in_wait_list,
1429
+ const cl_event * event_wait_list,
1430
+ cl_event * event) CL_API_SUFFIX__VERSION_1_0;
1431
+
1432
+ extern CL_API_ENTRY cl_int CL_API_CALL
1433
+ clEnqueueMarkerWithWaitList(cl_command_queue command_queue,
1434
+ cl_uint num_events_in_wait_list,
1435
+ const cl_event * event_wait_list,
1436
+ cl_event * event) CL_API_SUFFIX__VERSION_1_2;
1437
+
1438
+ extern CL_API_ENTRY cl_int CL_API_CALL
1439
+ clEnqueueBarrierWithWaitList(cl_command_queue command_queue,
1440
+ cl_uint num_events_in_wait_list,
1441
+ const cl_event * event_wait_list,
1442
+ cl_event * event) CL_API_SUFFIX__VERSION_1_2;
1443
+
1444
+ extern CL_API_ENTRY cl_int CL_API_CALL
1445
+ clEnqueueSVMFree(cl_command_queue command_queue,
1446
+ cl_uint num_svm_pointers,
1447
+ void * svm_pointers[],
1448
+ void (CL_CALLBACK * pfn_free_func)(cl_command_queue queue,
1449
+ cl_uint num_svm_pointers,
1450
+ void * svm_pointers[],
1451
+ void * user_data),
1452
+ void * user_data,
1453
+ cl_uint num_events_in_wait_list,
1454
+ const cl_event * event_wait_list,
1455
+ cl_event * event) CL_API_SUFFIX__VERSION_2_0;
1456
+
1457
+ extern CL_API_ENTRY cl_int CL_API_CALL
1458
+ clEnqueueSVMMemcpy(cl_command_queue command_queue,
1459
+ cl_bool blocking_copy,
1460
+ void * dst_ptr,
1461
+ const void * src_ptr,
1462
+ size_t size,
1463
+ cl_uint num_events_in_wait_list,
1464
+ const cl_event * event_wait_list,
1465
+ cl_event * event) CL_API_SUFFIX__VERSION_2_0;
1466
+
1467
+ extern CL_API_ENTRY cl_int CL_API_CALL
1468
+ clEnqueueSVMMemFill(cl_command_queue command_queue,
1469
+ void * svm_ptr,
1470
+ const void * pattern,
1471
+ size_t pattern_size,
1472
+ size_t size,
1473
+ cl_uint num_events_in_wait_list,
1474
+ const cl_event * event_wait_list,
1475
+ cl_event * event) CL_API_SUFFIX__VERSION_2_0;
1476
+
1477
+ extern CL_API_ENTRY cl_int CL_API_CALL
1478
+ clEnqueueSVMMap(cl_command_queue command_queue,
1479
+ cl_bool blocking_map,
1480
+ cl_map_flags flags,
1481
+ void * svm_ptr,
1482
+ size_t size,
1483
+ cl_uint num_events_in_wait_list,
1484
+ const cl_event * event_wait_list,
1485
+ cl_event * event) CL_API_SUFFIX__VERSION_2_0;
1486
+
1487
+ extern CL_API_ENTRY cl_int CL_API_CALL
1488
+ clEnqueueSVMUnmap(cl_command_queue command_queue,
1489
+ void * svm_ptr,
1490
+ cl_uint num_events_in_wait_list,
1491
+ const cl_event * event_wait_list,
1492
+ cl_event * event) CL_API_SUFFIX__VERSION_2_0;
1493
+
1494
+ extern CL_API_ENTRY cl_int CL_API_CALL
1495
+ clEnqueueSVMMigrateMem(cl_command_queue command_queue,
1496
+ cl_uint num_svm_pointers,
1497
+ const void ** svm_pointers,
1498
+ const size_t * sizes,
1499
+ cl_mem_migration_flags flags,
1500
+ cl_uint num_events_in_wait_list,
1501
+ const cl_event * event_wait_list,
1502
+ cl_event * event) CL_API_SUFFIX__VERSION_2_1;
1503
+
1504
+ /* Extension function access
1505
+ *
1506
+ * Returns the extension function address for the given function name,
1507
+ * or NULL if a valid function can not be found. The client must
1508
+ * check to make sure the address is not NULL, before using or
1509
+ * calling the returned function address.
1510
+ */
1511
+ extern CL_API_ENTRY void * CL_API_CALL
1512
+ clGetExtensionFunctionAddressForPlatform(cl_platform_id platform,
1513
+ const char * func_name) CL_API_SUFFIX__VERSION_1_2;
1514
+
1515
+ #ifdef CL_USE_DEPRECATED_OPENCL_1_0_APIS
1516
+ /*
1517
+ * WARNING:
1518
+ * This API introduces mutable state into the OpenCL implementation. It has been REMOVED
1519
+ * to better facilitate thread safety. The 1.0 API is not thread safe. It is not tested by the
1520
+ * OpenCL 1.1 conformance test, and consequently may not work or may not work dependably.
1521
+ * It is likely to be non-performant. Use of this API is not advised. Use at your own risk.
1522
+ *
1523
+ * Software developers previously relying on this API are instructed to set the command queue
1524
+ * properties when creating the queue, instead.
1525
+ */
1526
+ extern CL_API_ENTRY cl_int CL_API_CALL
1527
+ clSetCommandQueueProperty(cl_command_queue command_queue,
1528
+ cl_command_queue_properties properties,
1529
+ cl_bool enable,
1530
+ cl_command_queue_properties * old_properties) CL_EXT_SUFFIX__VERSION_1_0_DEPRECATED;
1531
+ #endif /* CL_USE_DEPRECATED_OPENCL_1_0_APIS */
1532
+
1533
+ /* Deprecated OpenCL 1.1 APIs */
1534
+ extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL
1535
+ clCreateImage2D(cl_context context,
1536
+ cl_mem_flags flags,
1537
+ const cl_image_format * image_format,
1538
+ size_t image_width,
1539
+ size_t image_height,
1540
+ size_t image_row_pitch,
1541
+ void * host_ptr,
1542
+ cl_int * errcode_ret) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED;
1543
+
1544
+ extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_mem CL_API_CALL
1545
+ clCreateImage3D(cl_context context,
1546
+ cl_mem_flags flags,
1547
+ const cl_image_format * image_format,
1548
+ size_t image_width,
1549
+ size_t image_height,
1550
+ size_t image_depth,
1551
+ size_t image_row_pitch,
1552
+ size_t image_slice_pitch,
1553
+ void * host_ptr,
1554
+ cl_int * errcode_ret) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED;
1555
+
1556
+ extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL
1557
+ clEnqueueMarker(cl_command_queue command_queue,
1558
+ cl_event * event) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED;
1559
+
1560
+ extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL
1561
+ clEnqueueWaitForEvents(cl_command_queue command_queue,
1562
+ cl_uint num_events,
1563
+ const cl_event * event_list) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED;
1564
+
1565
+ extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL
1566
+ clEnqueueBarrier(cl_command_queue command_queue) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED;
1567
+
1568
+ extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED cl_int CL_API_CALL
1569
+ clUnloadCompiler(void) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED;
1570
+
1571
+ extern CL_API_ENTRY CL_EXT_PREFIX__VERSION_1_1_DEPRECATED void * CL_API_CALL
1572
+ clGetExtensionFunctionAddress(const char * func_name) CL_EXT_SUFFIX__VERSION_1_1_DEPRECATED;
1573
+
1574
+ #ifdef __cplusplus
1575
+ }
1576
+ #endif
1577
+
1578
+ #endif /* __OPENCL_CL_H */
tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/CL/cl_ext.h ADDED
@@ -0,0 +1,1131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*******************************************************************************
2
+ * Copyright (c) 2008-2020 The Khronos Group Inc.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ ******************************************************************************/
16
+
17
+ /* cl_ext.h contains OpenCL extensions which don't have external */
18
+ /* (OpenGL, D3D) dependencies. */
19
+
20
+ #ifndef __CL_EXT_H
21
+ #define __CL_EXT_H
22
+
23
+ #ifdef __cplusplus
24
+ extern "C" {
25
+ #endif
26
+
27
+ #ifdef __APPLE__
28
+ #include <OpenCL/cl.h>
29
+ #include <AvailabilityMacros.h>
30
+ #else
31
+ #include <CL/cl.h>
32
+ #endif
33
+
34
+ /* cl_khr_fp64 extension - no extension #define since it has no functions */
35
+ /* CL_DEVICE_DOUBLE_FP_CONFIG is defined in CL.h for OpenCL >= 120 */
36
+ #define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032
37
+
38
+ /* cl_khr_fp16 extension - no extension #define since it has no functions */
39
+ #define CL_DEVICE_HALF_FP_CONFIG 0x1033
40
+
41
+ /* Memory object destruction
42
+ *
43
+ * Apple extension for use to manage externally allocated buffers used with cl_mem objects with CL_MEM_USE_HOST_PTR
44
+ *
45
+ * Registers a user callback function that will be called when the memory object is deleted and its resources
46
+ * freed. Each call to clSetMemObjectCallbackFn registers the specified user callback function on a callback
47
+ * stack associated with memobj. The registered user callback functions are called in the reverse order in
48
+ * which they were registered. The user callback functions are called and then the memory object is deleted
49
+ * and its resources freed. This provides a mechanism for the application (and libraries) using memobj to be
50
+ * notified when the memory referenced by host_ptr, specified when the memory object is created and used as
51
+ * the storage bits for the memory object, can be reused or freed.
52
+ *
53
+ * The application may not call CL api's with the cl_mem object passed to the pfn_notify.
54
+ *
55
+ * Please check for the "cl_APPLE_SetMemObjectDestructor" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS)
56
+ * before using.
57
+ */
58
+ #define cl_APPLE_SetMemObjectDestructor 1
59
+ cl_int CL_API_ENTRY clSetMemObjectDestructorAPPLE( cl_mem memobj,
60
+ void (* pfn_notify)(cl_mem memobj, void * user_data),
61
+ void * user_data) CL_EXT_SUFFIX__VERSION_1_0;
62
+
63
+
64
+ /* Context Logging Functions
65
+ *
66
+ * The next three convenience functions are intended to be used as the pfn_notify parameter to clCreateContext().
67
+ * Please check for the "cl_APPLE_ContextLoggingFunctions" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS)
68
+ * before using.
69
+ *
70
+ * clLogMessagesToSystemLog forwards on all log messages to the Apple System Logger
71
+ */
72
+ #define cl_APPLE_ContextLoggingFunctions 1
73
+ extern void CL_API_ENTRY clLogMessagesToSystemLogAPPLE( const char * errstr,
74
+ const void * private_info,
75
+ size_t cb,
76
+ void * user_data) CL_EXT_SUFFIX__VERSION_1_0;
77
+
78
+ /* clLogMessagesToStdout sends all log messages to the file descriptor stdout */
79
+ extern void CL_API_ENTRY clLogMessagesToStdoutAPPLE( const char * errstr,
80
+ const void * private_info,
81
+ size_t cb,
82
+ void * user_data) CL_EXT_SUFFIX__VERSION_1_0;
83
+
84
+ /* clLogMessagesToStderr sends all log messages to the file descriptor stderr */
85
+ extern void CL_API_ENTRY clLogMessagesToStderrAPPLE( const char * errstr,
86
+ const void * private_info,
87
+ size_t cb,
88
+ void * user_data) CL_EXT_SUFFIX__VERSION_1_0;
89
+
90
+
91
+ /************************
92
+ * cl_khr_icd extension *
93
+ ************************/
94
+ #define cl_khr_icd 1
95
+
96
+ /* cl_platform_info */
97
+ #define CL_PLATFORM_ICD_SUFFIX_KHR 0x0920
98
+
99
+ /* Additional Error Codes */
100
+ #define CL_PLATFORM_NOT_FOUND_KHR -1001
101
+
102
+ extern CL_API_ENTRY cl_int CL_API_CALL
103
+ clIcdGetPlatformIDsKHR(cl_uint num_entries,
104
+ cl_platform_id * platforms,
105
+ cl_uint * num_platforms);
106
+
107
+ typedef CL_API_ENTRY cl_int
108
+ (CL_API_CALL *clIcdGetPlatformIDsKHR_fn)(cl_uint num_entries,
109
+ cl_platform_id * platforms,
110
+ cl_uint * num_platforms);
111
+
112
+
113
+ /*******************************
114
+ * cl_khr_il_program extension *
115
+ *******************************/
116
+ #define cl_khr_il_program 1
117
+
118
+ /* New property to clGetDeviceInfo for retrieving supported intermediate
119
+ * languages
120
+ */
121
+ #define CL_DEVICE_IL_VERSION_KHR 0x105B
122
+
123
+ /* New property to clGetProgramInfo for retrieving for retrieving the IL of a
124
+ * program
125
+ */
126
+ #define CL_PROGRAM_IL_KHR 0x1169
127
+
128
+ extern CL_API_ENTRY cl_program CL_API_CALL
129
+ clCreateProgramWithILKHR(cl_context context,
130
+ const void * il,
131
+ size_t length,
132
+ cl_int * errcode_ret);
133
+
134
+ typedef CL_API_ENTRY cl_program
135
+ (CL_API_CALL *clCreateProgramWithILKHR_fn)(cl_context context,
136
+ const void * il,
137
+ size_t length,
138
+ cl_int * errcode_ret) CL_EXT_SUFFIX__VERSION_1_2;
139
+
140
+ /* Extension: cl_khr_image2d_from_buffer
141
+ *
142
+ * This extension allows a 2D image to be created from a cl_mem buffer without
143
+ * a copy. The type associated with a 2D image created from a buffer in an
144
+ * OpenCL program is image2d_t. Both the sampler and sampler-less read_image
145
+ * built-in functions are supported for 2D images and 2D images created from
146
+ * a buffer. Similarly, the write_image built-ins are also supported for 2D
147
+ * images created from a buffer.
148
+ *
149
+ * When the 2D image from buffer is created, the client must specify the
150
+ * width, height, image format (i.e. channel order and channel data type)
151
+ * and optionally the row pitch.
152
+ *
153
+ * The pitch specified must be a multiple of
154
+ * CL_DEVICE_IMAGE_PITCH_ALIGNMENT_KHR pixels.
155
+ * The base address of the buffer must be aligned to
156
+ * CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT_KHR pixels.
157
+ */
158
+
159
+ #define CL_DEVICE_IMAGE_PITCH_ALIGNMENT_KHR 0x104A
160
+ #define CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT_KHR 0x104B
161
+
162
+
163
+ /**************************************
164
+ * cl_khr_initialize_memory extension *
165
+ **************************************/
166
+
167
+ #define CL_CONTEXT_MEMORY_INITIALIZE_KHR 0x2030
168
+
169
+
170
+ /**************************************
171
+ * cl_khr_terminate_context extension *
172
+ **************************************/
173
+
174
+ #define CL_CONTEXT_TERMINATED_KHR -1121
175
+
176
+ #define CL_DEVICE_TERMINATE_CAPABILITY_KHR 0x2031
177
+ #define CL_CONTEXT_TERMINATE_KHR 0x2032
178
+
179
+ #define cl_khr_terminate_context 1
180
+ extern CL_API_ENTRY cl_int CL_API_CALL
181
+ clTerminateContextKHR(cl_context context) CL_EXT_SUFFIX__VERSION_1_2;
182
+
183
+ typedef CL_API_ENTRY cl_int
184
+ (CL_API_CALL *clTerminateContextKHR_fn)(cl_context context) CL_EXT_SUFFIX__VERSION_1_2;
185
+
186
+
187
+ /*
188
+ * Extension: cl_khr_spir
189
+ *
190
+ * This extension adds support to create an OpenCL program object from a
191
+ * Standard Portable Intermediate Representation (SPIR) instance
192
+ */
193
+
194
+ #define CL_DEVICE_SPIR_VERSIONS 0x40E0
195
+ #define CL_PROGRAM_BINARY_TYPE_INTERMEDIATE 0x40E1
196
+
197
+
198
+ /*****************************************
199
+ * cl_khr_create_command_queue extension *
200
+ *****************************************/
201
+ #define cl_khr_create_command_queue 1
202
+
203
+ typedef cl_properties cl_queue_properties_khr;
204
+
205
+ extern CL_API_ENTRY cl_command_queue CL_API_CALL
206
+ clCreateCommandQueueWithPropertiesKHR(cl_context context,
207
+ cl_device_id device,
208
+ const cl_queue_properties_khr* properties,
209
+ cl_int* errcode_ret) CL_EXT_SUFFIX__VERSION_1_2;
210
+
211
+ typedef CL_API_ENTRY cl_command_queue
212
+ (CL_API_CALL *clCreateCommandQueueWithPropertiesKHR_fn)(cl_context context,
213
+ cl_device_id device,
214
+ const cl_queue_properties_khr* properties,
215
+ cl_int* errcode_ret) CL_EXT_SUFFIX__VERSION_1_2;
216
+
217
+
218
+ /******************************************
219
+ * cl_khr_semaphore extension *
220
+ ******************************************/
221
+
222
+ typedef enum _cl_semaphore_type__enum {
223
+ CL_SEMAPHORE_TYPE_BINARY_KHR = 1,
224
+ } cl_semaphore_type;
225
+
226
+ typedef cl_properties cl_semaphore_properties_khr;
227
+
228
+ typedef cl_uint cl_semaphore_info_khr;
229
+
230
+ typedef struct _cl_semaphore* cl_semaphore_khr;
231
+ typedef cl_ulong cl_semaphore_payload_khr;
232
+
233
+ extern CL_API_ENTRY cl_semaphore_khr CL_API_CALL
234
+ clCreateSemaphoreWithPropertiesKHR(cl_context context,
235
+ cl_semaphore_properties_khr *sema_props,
236
+ cl_int *errcode_ret) CL_API_SUFFIX__VERSION_1_2;
237
+
238
+ extern CL_API_ENTRY cl_int CL_API_CALL
239
+ clEnqueueWaitSemaphoresKHR(cl_command_queue command_queue,
240
+ cl_uint num_sema_objects,
241
+ const cl_semaphore_khr *sema_objects,
242
+ const cl_semaphore_payload_khr *sema_payload_list,
243
+ cl_uint num_events_in_wait_list,
244
+ const cl_event *event_wait_list,
245
+ cl_event *event) CL_API_SUFFIX__VERSION_1_2;
246
+
247
+ extern CL_API_ENTRY cl_int CL_API_CALL
248
+ clEnqueueSignalSemaphoresKHR(cl_command_queue command_queue,
249
+ cl_uint num_sema_objects,
250
+ const cl_semaphore_khr *sema_objects,
251
+ const cl_semaphore_payload_khr *sema_payload_list,
252
+ cl_uint num_events_in_wait_list,
253
+ const cl_event *event_wait_list,
254
+ cl_event *event) CL_API_SUFFIX__VERSION_1_2;
255
+
256
+ extern CL_API_ENTRY cl_int CL_API_CALL
257
+ clGetSemaphoreInfoKHR(const cl_semaphore_khr sema_object,
258
+ cl_semaphore_info_khr param_name,
259
+ size_t param_value_size,
260
+ void *param_value,
261
+ size_t *param_value_size_ret) CL_API_SUFFIX__VERSION_1_2;
262
+
263
+ extern CL_API_ENTRY cl_int CL_API_CALL
264
+ clReleaseSemaphoreKHR(cl_semaphore_khr sema_object) CL_API_SUFFIX__VERSION_1_2;
265
+
266
+ extern CL_API_ENTRY cl_int CL_API_CALL
267
+ clRetainSemaphoreKHR(cl_semaphore_khr sema_object) CL_API_SUFFIX__VERSION_1_2;
268
+
269
+ extern CL_API_ENTRY cl_int CL_API_CALL
270
+ clReleaseSemaphoreObjectKHR(cl_semaphore_khr sema_object) CL_API_SUFFIX__VERSION_1_2;
271
+
272
+ #define CL_COMMAND_SEMAPHORE_WAIT_KHR 0x2042
273
+ #define CL_COMMAND_SEMAPHORE_SIGNAL_KHR 0x2043
274
+ #define CL_SEMAPHORE_CONTEXT_KHR 0x2039
275
+ #define CL_SEMAPHORE_REFERENCE_COUNT_KHR 0x203A
276
+ #define CL_SEMAPHORE_PROPERTIES_KHR 0x203B
277
+ #define CL_SEMAPHORE_TYPE_KHR 0x203D
278
+ #define CL_PLATFORM_SEMAPHORE_TYPES_KHR 0x2036
279
+ #define CL_SEMAPHORE_PAYLOAD_KHR 0x203C
280
+
281
+ /******************************************
282
+ * cl_khr_external_semaphore extension *
283
+ ******************************************/
284
+
285
+ typedef enum _cl_external_context_type_enum {
286
+ CL_EXTERNAL_CONTEXT_TYPE_NONE = 0,
287
+ CL_EXTERNAL_CONTEXT_TYPE_CL = 1,
288
+ CL_EXTERNAL_CONTEXT_TYPE_VULKAN = 2,
289
+ } cl_external_context_type_khr;
290
+
291
+ typedef cl_uint cl_external_semaphore_handle_type_khr;
292
+ // API-agnostic semaphore handles are defined here in this spec.
293
+ #define CL_SEMAPHORE_HANDLE_OPAQUE_FD_KHR 0x2055
294
+ #define CL_SEMAPHORE_HANDLE_OPAQUE_WIN32_KHR 0x2056
295
+ #define CL_SEMAPHORE_HANDLE_OPAQUE_WIN32_KMT_KHR 0x2057
296
+
297
+ typedef struct _cl_semaphore_desc_khr_st {
298
+ cl_external_semaphore_handle_type_khr type;
299
+ void *handle_ptr;
300
+ } cl_semaphore_desc_khr;
301
+
302
+ extern CL_API_ENTRY cl_int CL_API_CALL
303
+ clGetSemaphoreHandleForTypeKHR(const cl_semaphore_khr sema_object,
304
+ const cl_device_id device,
305
+ cl_external_semaphore_handle_type_khr handle_type,
306
+ size_t handle_size,
307
+ void *handle_ptr,
308
+ size_t *handle_size_ret) CL_API_SUFFIX__VERSION_1_2;
309
+
310
+ #define CL_SEMAPHORE_DESC_KHR 0x2460
311
+ #define CL_SEMAPHORE_EXPORT_HANDLE_TYPES_KHR 0x203F
312
+
313
+ #define CL_PLATFORM_SEMAPHORE_IMPORT_HANDLE_TYPES_KHR 0x2037
314
+ #define CL_PLATFORM_SEMAPHORE_EXPORT_HANDLE_TYPES_KHR 0x2038
315
+
316
+ #define CL_DEVICE_SEMAPHORE_IMPORT_HANDLE_TYPES_KHR 0x204D
317
+ #define CL_DEVICE_SEMAPHORE_EXPORT_HANDLE_TYPES_KHR 0x204E
318
+
319
+ // error codes
320
+ #define CL_INVALID_SEMAPHORE_KHR -1142
321
+
322
+ /******************************************
323
+ * cl_khr_external_memory extension *
324
+ ******************************************/
325
+
326
+ typedef cl_uint cl_external_context_info;
327
+
328
+ typedef enum _cl_external_context_type_enum cl_external_context_type_khr;
329
+
330
+ typedef cl_properties cl_mem_properties_khr;
331
+
332
+ typedef cl_uint cl_external_mem_handle_type_khr;
333
+ // API-agnostic memory handles are defined here in this spec.
334
+ #define CL_EXTERNAL_MEMORY_HANDLE_OPAQUE_FD_KHR 0x2060
335
+ #define CL_EXTERNAL_MEMORY_HANDLE_OPAQUE_WIN32_KHR 0x2061
336
+ #define CL_EXTERNAL_MEMORY_HANDLE_OPAQUE_WIN32_KMT_KHR 0x2062
337
+
338
+ typedef struct _cl_external_mem_desc_khr_st {
339
+ cl_external_mem_handle_type_khr type;
340
+ void *handle_ptr;
341
+ size_t offset;
342
+ unsigned long long size;
343
+ } cl_external_mem_desc_khr;
344
+
345
+ extern CL_API_ENTRY cl_int CL_API_CALL
346
+ clGetExternalContextInfoKHR(const cl_context_properties *properties,
347
+ cl_external_context_info param_name,
348
+ size_t param_value_size,
349
+ void *param_value,
350
+ size_t *param_value_size_ret) CL_API_SUFFIX__VERSION_1_2;
351
+
352
+ extern CL_API_ENTRY cl_int CL_API_CALL
353
+ clEnqueueAcquireExternalMemObjectsKHR(cl_command_queue command_queue,
354
+ cl_uint num_mem_objects,
355
+ const cl_mem *mem_objects,
356
+ cl_uint num_events_in_wait_list,
357
+ const cl_event *event_wait_list,
358
+ cl_event *event) CL_API_SUFFIX__VERSION_1_2;
359
+
360
+ extern CL_API_ENTRY cl_int CL_API_CALL
361
+ clEnqueueReleaseExternalMemObjectsKHR(cl_command_queue command_queue,
362
+ cl_uint num_mem_objects,
363
+ const cl_mem *mem_objects,
364
+ cl_uint num_events_in_wait_list,
365
+ const cl_event *event_wait_list,
366
+ cl_event *event) CL_API_SUFFIX__VERSION_1_2;
367
+
368
+ extern CL_API_ENTRY cl_mem CL_API_CALL
369
+ clCreateBufferFromExternalMemoryKHR(cl_context context,
370
+ const cl_mem_properties_khr* properties,
371
+ cl_mem_flags flags,
372
+ cl_external_mem_desc_khr extMem,
373
+ cl_int *errcode_ret) CL_API_SUFFIX__VERSION_1_2;
374
+
375
+ extern CL_API_ENTRY cl_mem CL_API_CALL
376
+ clCreateImageFromExternalMemoryKHR(cl_context context,
377
+ const cl_mem_properties_khr* properties,
378
+ cl_mem_flags flags,
379
+ cl_external_mem_desc_khr extMem,
380
+ const cl_image_format *image_format,
381
+ const cl_image_desc *image_desc,
382
+ cl_int *errcode_ret) CL_API_SUFFIX__VERSION_1_2;
383
+
384
+ extern CL_API_ENTRY cl_semaphore_khr CL_API_CALL
385
+ clCreateFromExternalSemaphoreKHR(cl_context context,
386
+ cl_semaphore_properties_khr *sema_props,
387
+ cl_semaphore_desc_khr sema_desc,
388
+ cl_int *errcode_ret)
389
+ CL_API_SUFFIX__VERSION_1_2;
390
+
391
+ #define CL_INVALID_EXTERNAL_DEVICEGROUP_REFERENCE_KHR -1122
392
+ #define CL_INVALID_EXT_MEM_DESC_KHR -1123
393
+ #define CL_INVALID_EXT_MEM_HANDLE_TYPE_KHR -1148
394
+ #define CL_INVALID_EXT_MEM_HANDLE_KHR -1149
395
+ #define CL_INVALID_EXT_MEM_OFFSET_KHR -1150
396
+ #define CL_INVALID_EXT_MEM_SIZE_KHR -1140
397
+
398
+ #define CL_CURRENT_DEVICE_FOR_EXTERNAL_CONTEXT_KHR 0x2036
399
+ #define CL_DEVICES_FOR_EXTERNAL_CONTEXT_KHR 0x2037
400
+ #define CL_EXTERNAL_DEVICE_KHR 0x2038
401
+ #define CL_EXTERNAL_DEVICEGROUP_KHR 0x2039
402
+ #define CL_EXTERNAL_CONTEXT_TYPE_KHR 0x204B
403
+ #define CL_DEVICE_HANDLE_LIST_KHR 0x2051
404
+ #define CL_DEVICE_HANDLE_LIST_END_KHR 0x0
405
+
406
+
407
+ #define CL_COMMAND_ACQUIRE_EXTERNAL_MEM_OBJECTS_KHR 0x2047
408
+ #define CL_COMMAND_RELEASE_EXTERNAL_MEM_OBJECTS_KHR 0x2048
409
+ #define CL_EXTERNAL_MEM_DESC_KHR 0x203C
410
+ #define CL_EXTERNAL_IMAGE_INFO_KHR 0x203D
411
+ #define CL_PLATFORM_EXTERNAL_HANDLE_TYPES_KHR 0x203E
412
+ #define CL_PLATFORM_EXTERNAL_MEMORY_IMPORT_HANDLE_TYPES_KHR 0x2044
413
+ #define CL_DEVICE_EXTERNAL_MEMORY_IMPORT_HANDLE_TYPES_KHR 0x204F
414
+ #define CL_DEVICE_EXTERNAL_MEMORY_PROPERTIES_KHR 0x2050
415
+
416
+
417
+ /******************************************
418
+ * cl_nv_device_attribute_query extension *
419
+ ******************************************/
420
+
421
+ /* cl_nv_device_attribute_query extension - no extension #define since it has no functions */
422
+ #define CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV 0x4000
423
+ #define CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV 0x4001
424
+ #define CL_DEVICE_REGISTERS_PER_BLOCK_NV 0x4002
425
+ #define CL_DEVICE_WARP_SIZE_NV 0x4003
426
+ #define CL_DEVICE_GPU_OVERLAP_NV 0x4004
427
+ #define CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV 0x4005
428
+ #define CL_DEVICE_INTEGRATED_MEMORY_NV 0x4006
429
+ #define CL_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT_NV 0x4007
430
+ #define CL_DEVICE_PCI_BUS_ID_NV 0x4008
431
+ #define CL_DEVICE_PCI_SLOT_ID_NV 0x4009
432
+ #define CL_DEVICE_PCI_DOMAIN_ID_NV 0x400A
433
+ #define CL_DEVICE_MAX_LOCAL_MEMORY_PER_SM_NV 0x400B
434
+ #define CL_DEVICE_UUID_KHR 0x106A
435
+ #define CL_DRIVER_UUID_KHR 0x106B
436
+ #define CL_DEVICE_LUID_VALID_KHR 0x106C
437
+ #define CL_DEVICE_LUID_KHR 0x106D
438
+ #define CL_DEVICE_NODE_MASK_KHR 0x106E
439
+ #define CL_UUID_SIZE_KHR 16
440
+ #define CL_LUID_SIZE_KHR 8
441
+
442
+ /******************************************
443
+ * cl_nv_create_buffer extension *
444
+ ******************************************/
445
+
446
+ typedef cl_bitfield cl_mem_flags_NV;
447
+ CL_API_ENTRY cl_mem CL_API_CALL
448
+ clCreateBufferNV(cl_context context,
449
+ cl_mem_flags flags,
450
+ cl_mem_flags_NV flags_NV,
451
+ size_t size,
452
+ void *host_ptr,
453
+ cl_int *errcode_ret);
454
+
455
+ /******************************************
456
+ * cl_kernel_attribute_nv extension *
457
+ *******************************************/
458
+
459
+ typedef enum kernel_attribute_enum {
460
+ CL_KERNEL_PREFERRED_LOCAL_MEMORY_SIZE_NV = 0, /* setting preferred shared memory size */
461
+ } cl_kernel_attribute_nv;
462
+
463
+ CL_API_ENTRY cl_int CL_API_CALL
464
+ clSetKernelAttributeNV(cl_kernel kernel,
465
+ cl_device_id device,
466
+ cl_kernel_attribute_nv k_attr,
467
+ size_t param_value_size,
468
+ const void *param_value);
469
+
470
+ CL_API_ENTRY cl_int CL_API_CALL
471
+ clGetKernelAttributeNV(cl_kernel kernel,
472
+ cl_device_id device,
473
+ cl_kernel_attribute_nv k_attr,
474
+ size_t param_value_size,
475
+ void *param_value,
476
+ size_t *param_value_size_ret);
477
+
478
+ #define CL_MEM_LOCATION_HOST_NV (1 << 0)
479
+ #define CL_MEM_PINNED_NV (1 << 1)
480
+
481
+ /*********************************
482
+ * cl_amd_device_attribute_query *
483
+ *********************************/
484
+
485
+ #define CL_DEVICE_PROFILING_TIMER_OFFSET_AMD 0x4036
486
+ #define CL_DEVICE_TOPOLOGY_AMD 0x4037
487
+ #define CL_DEVICE_BOARD_NAME_AMD 0x4038
488
+ #define CL_DEVICE_GLOBAL_FREE_MEMORY_AMD 0x4039
489
+ #define CL_DEVICE_SIMD_PER_COMPUTE_UNIT_AMD 0x4040
490
+ #define CL_DEVICE_SIMD_WIDTH_AMD 0x4041
491
+ #define CL_DEVICE_SIMD_INSTRUCTION_WIDTH_AMD 0x4042
492
+ #define CL_DEVICE_WAVEFRONT_WIDTH_AMD 0x4043
493
+ #define CL_DEVICE_GLOBAL_MEM_CHANNELS_AMD 0x4044
494
+ #define CL_DEVICE_GLOBAL_MEM_CHANNEL_BANKS_AMD 0x4045
495
+ #define CL_DEVICE_GLOBAL_MEM_CHANNEL_BANK_WIDTH_AMD 0x4046
496
+ #define CL_DEVICE_LOCAL_MEM_SIZE_PER_COMPUTE_UNIT_AMD 0x4047
497
+ #define CL_DEVICE_LOCAL_MEM_BANKS_AMD 0x4048
498
+ #define CL_DEVICE_THREAD_TRACE_SUPPORTED_AMD 0x4049
499
+ #define CL_DEVICE_GFXIP_MAJOR_AMD 0x404A
500
+ #define CL_DEVICE_GFXIP_MINOR_AMD 0x404B
501
+ #define CL_DEVICE_AVAILABLE_ASYNC_QUEUES_AMD 0x404C
502
+ #define CL_DEVICE_PREFERRED_WORK_GROUP_SIZE_AMD 0x4030
503
+ #define CL_DEVICE_MAX_WORK_GROUP_SIZE_AMD 0x4031
504
+ #define CL_DEVICE_PREFERRED_CONSTANT_BUFFER_SIZE_AMD 0x4033
505
+ #define CL_DEVICE_PCIE_ID_AMD 0x4034
506
+
507
+
508
+ /*********************************
509
+ * cl_arm_printf extension
510
+ *********************************/
511
+
512
+ #define CL_PRINTF_CALLBACK_ARM 0x40B0
513
+ #define CL_PRINTF_BUFFERSIZE_ARM 0x40B1
514
+
515
+
516
+ /***********************************
517
+ * cl_ext_device_fission extension
518
+ ***********************************/
519
+ #define cl_ext_device_fission 1
520
+
521
+ extern CL_API_ENTRY cl_int CL_API_CALL
522
+ clReleaseDeviceEXT(cl_device_id device) CL_EXT_SUFFIX__VERSION_1_1;
523
+
524
+ typedef CL_API_ENTRY cl_int
525
+ (CL_API_CALL *clReleaseDeviceEXT_fn)(cl_device_id device) CL_EXT_SUFFIX__VERSION_1_1;
526
+
527
+ extern CL_API_ENTRY cl_int CL_API_CALL
528
+ clRetainDeviceEXT(cl_device_id device) CL_EXT_SUFFIX__VERSION_1_1;
529
+
530
+ typedef CL_API_ENTRY cl_int
531
+ (CL_API_CALL *clRetainDeviceEXT_fn)(cl_device_id device) CL_EXT_SUFFIX__VERSION_1_1;
532
+
533
+ typedef cl_ulong cl_device_partition_property_ext;
534
+ extern CL_API_ENTRY cl_int CL_API_CALL
535
+ clCreateSubDevicesEXT(cl_device_id in_device,
536
+ const cl_device_partition_property_ext * properties,
537
+ cl_uint num_entries,
538
+ cl_device_id * out_devices,
539
+ cl_uint * num_devices) CL_EXT_SUFFIX__VERSION_1_1;
540
+
541
+ typedef CL_API_ENTRY cl_int
542
+ (CL_API_CALL * clCreateSubDevicesEXT_fn)(cl_device_id in_device,
543
+ const cl_device_partition_property_ext * properties,
544
+ cl_uint num_entries,
545
+ cl_device_id * out_devices,
546
+ cl_uint * num_devices) CL_EXT_SUFFIX__VERSION_1_1;
547
+
548
+ /* cl_device_partition_property_ext */
549
+ #define CL_DEVICE_PARTITION_EQUALLY_EXT 0x4050
550
+ #define CL_DEVICE_PARTITION_BY_COUNTS_EXT 0x4051
551
+ #define CL_DEVICE_PARTITION_BY_NAMES_EXT 0x4052
552
+ #define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT 0x4053
553
+
554
+ /* clDeviceGetInfo selectors */
555
+ #define CL_DEVICE_PARENT_DEVICE_EXT 0x4054
556
+ #define CL_DEVICE_PARTITION_TYPES_EXT 0x4055
557
+ #define CL_DEVICE_AFFINITY_DOMAINS_EXT 0x4056
558
+ #define CL_DEVICE_REFERENCE_COUNT_EXT 0x4057
559
+ #define CL_DEVICE_PARTITION_STYLE_EXT 0x4058
560
+
561
+ /* error codes */
562
+ #define CL_DEVICE_PARTITION_FAILED_EXT -1057
563
+ #define CL_INVALID_PARTITION_COUNT_EXT -1058
564
+ #define CL_INVALID_PARTITION_NAME_EXT -1059
565
+
566
+ /* CL_AFFINITY_DOMAINs */
567
+ #define CL_AFFINITY_DOMAIN_L1_CACHE_EXT 0x1
568
+ #define CL_AFFINITY_DOMAIN_L2_CACHE_EXT 0x2
569
+ #define CL_AFFINITY_DOMAIN_L3_CACHE_EXT 0x3
570
+ #define CL_AFFINITY_DOMAIN_L4_CACHE_EXT 0x4
571
+ #define CL_AFFINITY_DOMAIN_NUMA_EXT 0x10
572
+ #define CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT 0x100
573
+
574
+ /* cl_device_partition_property_ext list terminators */
575
+ #define CL_PROPERTIES_LIST_END_EXT ((cl_device_partition_property_ext) 0)
576
+ #define CL_PARTITION_BY_COUNTS_LIST_END_EXT ((cl_device_partition_property_ext) 0)
577
+ #define CL_PARTITION_BY_NAMES_LIST_END_EXT ((cl_device_partition_property_ext) 0 - 1)
578
+
579
+
580
+ /***********************************
581
+ * cl_ext_migrate_memobject extension definitions
582
+ ***********************************/
583
+ #define cl_ext_migrate_memobject 1
584
+
585
+ typedef cl_bitfield cl_mem_migration_flags_ext;
586
+
587
+ #define CL_MIGRATE_MEM_OBJECT_HOST_EXT 0x1
588
+
589
+ #define CL_COMMAND_MIGRATE_MEM_OBJECT_EXT 0x4040
590
+
591
+ extern CL_API_ENTRY cl_int CL_API_CALL
592
+ clEnqueueMigrateMemObjectEXT(cl_command_queue command_queue,
593
+ cl_uint num_mem_objects,
594
+ const cl_mem * mem_objects,
595
+ cl_mem_migration_flags_ext flags,
596
+ cl_uint num_events_in_wait_list,
597
+ const cl_event * event_wait_list,
598
+ cl_event * event);
599
+
600
+ typedef CL_API_ENTRY cl_int
601
+ (CL_API_CALL *clEnqueueMigrateMemObjectEXT_fn)(cl_command_queue command_queue,
602
+ cl_uint num_mem_objects,
603
+ const cl_mem * mem_objects,
604
+ cl_mem_migration_flags_ext flags,
605
+ cl_uint num_events_in_wait_list,
606
+ const cl_event * event_wait_list,
607
+ cl_event * event);
608
+
609
+
610
+ /*********************************
611
+ * cl_ext_cxx_for_opencl extension
612
+ *********************************/
613
+ #define cl_ext_cxx_for_opencl 1
614
+
615
+ #define CL_DEVICE_CXX_FOR_OPENCL_NUMERIC_VERSION_EXT 0x4230
616
+
617
+ /*********************************
618
+ * cl_qcom_ext_host_ptr extension
619
+ *********************************/
620
+ #define cl_qcom_ext_host_ptr 1
621
+
622
+ #define CL_MEM_EXT_HOST_PTR_QCOM (1 << 29)
623
+
624
+ #define CL_DEVICE_EXT_MEM_PADDING_IN_BYTES_QCOM 0x40A0
625
+ #define CL_DEVICE_PAGE_SIZE_QCOM 0x40A1
626
+ #define CL_IMAGE_ROW_ALIGNMENT_QCOM 0x40A2
627
+ #define CL_IMAGE_SLICE_ALIGNMENT_QCOM 0x40A3
628
+ #define CL_MEM_HOST_UNCACHED_QCOM 0x40A4
629
+ #define CL_MEM_HOST_WRITEBACK_QCOM 0x40A5
630
+ #define CL_MEM_HOST_WRITETHROUGH_QCOM 0x40A6
631
+ #define CL_MEM_HOST_WRITE_COMBINING_QCOM 0x40A7
632
+
633
+ typedef cl_uint cl_image_pitch_info_qcom;
634
+
635
+ extern CL_API_ENTRY cl_int CL_API_CALL
636
+ clGetDeviceImageInfoQCOM(cl_device_id device,
637
+ size_t image_width,
638
+ size_t image_height,
639
+ const cl_image_format *image_format,
640
+ cl_image_pitch_info_qcom param_name,
641
+ size_t param_value_size,
642
+ void *param_value,
643
+ size_t *param_value_size_ret);
644
+
645
+ typedef struct _cl_mem_ext_host_ptr
646
+ {
647
+ /* Type of external memory allocation. */
648
+ /* Legal values will be defined in layered extensions. */
649
+ cl_uint allocation_type;
650
+
651
+ /* Host cache policy for this external memory allocation. */
652
+ cl_uint host_cache_policy;
653
+
654
+ } cl_mem_ext_host_ptr;
655
+
656
+
657
+ /*******************************************
658
+ * cl_qcom_ext_host_ptr_iocoherent extension
659
+ ********************************************/
660
+
661
+ /* Cache policy specifying io-coherence */
662
+ #define CL_MEM_HOST_IOCOHERENT_QCOM 0x40A9
663
+
664
+
665
+ /*********************************
666
+ * cl_qcom_ion_host_ptr extension
667
+ *********************************/
668
+
669
+ #define CL_MEM_ION_HOST_PTR_QCOM 0x40A8
670
+
671
+ typedef struct _cl_mem_ion_host_ptr
672
+ {
673
+ /* Type of external memory allocation. */
674
+ /* Must be CL_MEM_ION_HOST_PTR_QCOM for ION allocations. */
675
+ cl_mem_ext_host_ptr ext_host_ptr;
676
+
677
+ /* ION file descriptor */
678
+ int ion_filedesc;
679
+
680
+ /* Host pointer to the ION allocated memory */
681
+ void* ion_hostptr;
682
+
683
+ } cl_mem_ion_host_ptr;
684
+
685
+
686
+ /*********************************
687
+ * cl_qcom_android_native_buffer_host_ptr extension
688
+ *********************************/
689
+
690
+ #define CL_MEM_ANDROID_NATIVE_BUFFER_HOST_PTR_QCOM 0x40C6
691
+
692
+ typedef struct _cl_mem_android_native_buffer_host_ptr
693
+ {
694
+ /* Type of external memory allocation. */
695
+ /* Must be CL_MEM_ANDROID_NATIVE_BUFFER_HOST_PTR_QCOM for Android native buffers. */
696
+ cl_mem_ext_host_ptr ext_host_ptr;
697
+
698
+ /* Virtual pointer to the android native buffer */
699
+ void* anb_ptr;
700
+
701
+ } cl_mem_android_native_buffer_host_ptr;
702
+
703
+
704
+ /******************************************
705
+ * cl_img_yuv_image extension *
706
+ ******************************************/
707
+
708
+ /* Image formats used in clCreateImage */
709
+ #define CL_NV21_IMG 0x40D0
710
+ #define CL_YV12_IMG 0x40D1
711
+
712
+
713
+ /******************************************
714
+ * cl_img_cached_allocations extension *
715
+ ******************************************/
716
+
717
+ /* Flag values used by clCreateBuffer */
718
+ #define CL_MEM_USE_UNCACHED_CPU_MEMORY_IMG (1 << 26)
719
+ #define CL_MEM_USE_CACHED_CPU_MEMORY_IMG (1 << 27)
720
+
721
+
722
+ /******************************************
723
+ * cl_img_use_gralloc_ptr extension *
724
+ ******************************************/
725
+ #define cl_img_use_gralloc_ptr 1
726
+
727
+ /* Flag values used by clCreateBuffer */
728
+ #define CL_MEM_USE_GRALLOC_PTR_IMG (1 << 28)
729
+
730
+ /* To be used by clGetEventInfo: */
731
+ #define CL_COMMAND_ACQUIRE_GRALLOC_OBJECTS_IMG 0x40D2
732
+ #define CL_COMMAND_RELEASE_GRALLOC_OBJECTS_IMG 0x40D3
733
+
734
+ /* Error code from clEnqueueReleaseGrallocObjectsIMG */
735
+ #define CL_GRALLOC_RESOURCE_NOT_ACQUIRED_IMG 0x40D4
736
+
737
+ extern CL_API_ENTRY cl_int CL_API_CALL
738
+ clEnqueueAcquireGrallocObjectsIMG(cl_command_queue command_queue,
739
+ cl_uint num_objects,
740
+ const cl_mem * mem_objects,
741
+ cl_uint num_events_in_wait_list,
742
+ const cl_event * event_wait_list,
743
+ cl_event * event) CL_EXT_SUFFIX__VERSION_1_2;
744
+
745
+ extern CL_API_ENTRY cl_int CL_API_CALL
746
+ clEnqueueReleaseGrallocObjectsIMG(cl_command_queue command_queue,
747
+ cl_uint num_objects,
748
+ const cl_mem * mem_objects,
749
+ cl_uint num_events_in_wait_list,
750
+ const cl_event * event_wait_list,
751
+ cl_event * event) CL_EXT_SUFFIX__VERSION_1_2;
752
+
753
+
754
+ /*********************************
755
+ * cl_khr_subgroups extension
756
+ *********************************/
757
+ #define cl_khr_subgroups 1
758
+
759
+ #if !defined(CL_VERSION_2_1)
760
+ /* For OpenCL 2.1 and newer, cl_kernel_sub_group_info is declared in CL.h.
761
+ In hindsight, there should have been a khr suffix on this type for
762
+ the extension, but keeping it un-suffixed to maintain backwards
763
+ compatibility. */
764
+ typedef cl_uint cl_kernel_sub_group_info;
765
+ #endif
766
+
767
+ /* cl_kernel_sub_group_info */
768
+ #define CL_KERNEL_MAX_SUB_GROUP_SIZE_FOR_NDRANGE_KHR 0x2033
769
+ #define CL_KERNEL_SUB_GROUP_COUNT_FOR_NDRANGE_KHR 0x2034
770
+
771
+ extern CL_API_ENTRY cl_int CL_API_CALL
772
+ clGetKernelSubGroupInfoKHR(cl_kernel in_kernel,
773
+ cl_device_id in_device,
774
+ cl_kernel_sub_group_info param_name,
775
+ size_t input_value_size,
776
+ const void * input_value,
777
+ size_t param_value_size,
778
+ void * param_value,
779
+ size_t * param_value_size_ret) CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED;
780
+
781
+ typedef CL_API_ENTRY cl_int
782
+ (CL_API_CALL * clGetKernelSubGroupInfoKHR_fn)(cl_kernel in_kernel,
783
+ cl_device_id in_device,
784
+ cl_kernel_sub_group_info param_name,
785
+ size_t input_value_size,
786
+ const void * input_value,
787
+ size_t param_value_size,
788
+ void * param_value,
789
+ size_t * param_value_size_ret) CL_EXT_SUFFIX__VERSION_2_0_DEPRECATED;
790
+
791
+
792
+ /*********************************
793
+ * cl_khr_mipmap_image extension
794
+ *********************************/
795
+
796
+ /* cl_sampler_properties */
797
+ #define CL_SAMPLER_MIP_FILTER_MODE_KHR 0x1155
798
+ #define CL_SAMPLER_LOD_MIN_KHR 0x1156
799
+ #define CL_SAMPLER_LOD_MAX_KHR 0x1157
800
+
801
+
802
+ /*********************************
803
+ * cl_khr_priority_hints extension
804
+ *********************************/
805
+ /* This extension define is for backwards compatibility.
806
+ It shouldn't be required since this extension has no new functions. */
807
+ #define cl_khr_priority_hints 1
808
+
809
+ typedef cl_uint cl_queue_priority_khr;
810
+
811
+ /* cl_command_queue_properties */
812
+ #define CL_QUEUE_PRIORITY_KHR 0x1096
813
+
814
+ /* cl_queue_priority_khr */
815
+ #define CL_QUEUE_PRIORITY_HIGH_KHR (1<<0)
816
+ #define CL_QUEUE_PRIORITY_MED_KHR (1<<1)
817
+ #define CL_QUEUE_PRIORITY_LOW_KHR (1<<2)
818
+
819
+
820
+ /*********************************
821
+ * cl_khr_throttle_hints extension
822
+ *********************************/
823
+ /* This extension define is for backwards compatibility.
824
+ It shouldn't be required since this extension has no new functions. */
825
+ #define cl_khr_throttle_hints 1
826
+
827
+ typedef cl_uint cl_queue_throttle_khr;
828
+
829
+ /* cl_command_queue_properties */
830
+ #define CL_QUEUE_THROTTLE_KHR 0x1097
831
+
832
+ /* cl_queue_throttle_khr */
833
+ #define CL_QUEUE_THROTTLE_HIGH_KHR (1<<0)
834
+ #define CL_QUEUE_THROTTLE_MED_KHR (1<<1)
835
+ #define CL_QUEUE_THROTTLE_LOW_KHR (1<<2)
836
+
837
+
838
+ /*********************************
839
+ * cl_khr_subgroup_named_barrier
840
+ *********************************/
841
+ /* This extension define is for backwards compatibility.
842
+ It shouldn't be required since this extension has no new functions. */
843
+ #define cl_khr_subgroup_named_barrier 1
844
+
845
+ /* cl_device_info */
846
+ #define CL_DEVICE_MAX_NAMED_BARRIER_COUNT_KHR 0x2035
847
+
848
+
849
+ /*********************************
850
+ * cl_khr_extended_versioning
851
+ *********************************/
852
+
853
+ #define cl_khr_extended_versioning 1
854
+
855
+ #define CL_VERSION_MAJOR_BITS_KHR (10)
856
+ #define CL_VERSION_MINOR_BITS_KHR (10)
857
+ #define CL_VERSION_PATCH_BITS_KHR (12)
858
+
859
+ #define CL_VERSION_MAJOR_MASK_KHR ((1 << CL_VERSION_MAJOR_BITS_KHR) - 1)
860
+ #define CL_VERSION_MINOR_MASK_KHR ((1 << CL_VERSION_MINOR_BITS_KHR) - 1)
861
+ #define CL_VERSION_PATCH_MASK_KHR ((1 << CL_VERSION_PATCH_BITS_KHR) - 1)
862
+
863
+ #define CL_VERSION_MAJOR_KHR(version) ((version) >> (CL_VERSION_MINOR_BITS_KHR + CL_VERSION_PATCH_BITS_KHR))
864
+ #define CL_VERSION_MINOR_KHR(version) (((version) >> CL_VERSION_PATCH_BITS_KHR) & CL_VERSION_MINOR_MASK_KHR)
865
+ #define CL_VERSION_PATCH_KHR(version) ((version) & CL_VERSION_PATCH_MASK_KHR)
866
+
867
+ #define CL_MAKE_VERSION_KHR(major, minor, patch) \
868
+ ((((major) & CL_VERSION_MAJOR_MASK_KHR) << (CL_VERSION_MINOR_BITS_KHR + CL_VERSION_PATCH_BITS_KHR)) | \
869
+ (((minor) & CL_VERSION_MINOR_MASK_KHR) << CL_VERSION_PATCH_BITS_KHR) | \
870
+ ((patch) & CL_VERSION_PATCH_MASK_KHR))
871
+
872
+ typedef cl_uint cl_version_khr;
873
+
874
+ #define CL_NAME_VERSION_MAX_NAME_SIZE_KHR 64
875
+
876
+ typedef struct _cl_name_version_khr
877
+ {
878
+ cl_version_khr version;
879
+ char name[CL_NAME_VERSION_MAX_NAME_SIZE_KHR];
880
+ } cl_name_version_khr;
881
+
882
+ /* cl_platform_info */
883
+ #define CL_PLATFORM_NUMERIC_VERSION_KHR 0x0906
884
+ #define CL_PLATFORM_EXTENSIONS_WITH_VERSION_KHR 0x0907
885
+
886
+ /* cl_device_info */
887
+ #define CL_DEVICE_NUMERIC_VERSION_KHR 0x105E
888
+ #define CL_DEVICE_OPENCL_C_NUMERIC_VERSION_KHR 0x105F
889
+ #define CL_DEVICE_EXTENSIONS_WITH_VERSION_KHR 0x1060
890
+ #define CL_DEVICE_ILS_WITH_VERSION_KHR 0x1061
891
+ #define CL_DEVICE_BUILT_IN_KERNELS_WITH_VERSION_KHR 0x1062
892
+
893
+
894
+ /*********************************
895
+ * cl_khr_device_uuid extension
896
+ *********************************/
897
+ #define cl_khr_device_uuid 1
898
+
899
+ #define CL_UUID_SIZE_KHR 16
900
+ #define CL_LUID_SIZE_KHR 8
901
+
902
+ #define CL_DEVICE_UUID_KHR 0x106A
903
+ #define CL_DRIVER_UUID_KHR 0x106B
904
+ #define CL_DEVICE_LUID_VALID_KHR 0x106C
905
+ #define CL_DEVICE_LUID_KHR 0x106D
906
+ #define CL_DEVICE_NODE_MASK_KHR 0x106E
907
+
908
+ /**********************************
909
+ * cl_khr_pci_bus_info extension *
910
+ **********************************/
911
+ #define cl_khr_pci_bus_info 1
912
+
913
+ #define CL_DEVICE_PCI_BUS_INFO_KHR 0x410F
914
+
915
+ typedef struct _cl_device_pci_bus_info_khr {
916
+ cl_uint pci_domain;
917
+ cl_uint pci_bus;
918
+ cl_uint pci_device;
919
+ cl_uint pci_function;
920
+ } cl_device_pci_bus_info_khr;
921
+
922
+ /**********************************
923
+ * cl_arm_import_memory extension *
924
+ **********************************/
925
+ #define cl_arm_import_memory 1
926
+
927
+ typedef intptr_t cl_import_properties_arm;
928
+
929
+ /* Default and valid proporties name for cl_arm_import_memory */
930
+ #define CL_IMPORT_TYPE_ARM 0x40B2
931
+
932
+ /* Host process memory type default value for CL_IMPORT_TYPE_ARM property */
933
+ #define CL_IMPORT_TYPE_HOST_ARM 0x40B3
934
+
935
+ /* DMA BUF memory type value for CL_IMPORT_TYPE_ARM property */
936
+ #define CL_IMPORT_TYPE_DMA_BUF_ARM 0x40B4
937
+
938
+ /* Protected memory property */
939
+ #define CL_IMPORT_TYPE_PROTECTED_ARM 0x40B5
940
+
941
+ /* Android hardware buffer type value for CL_IMPORT_TYPE_ARM property */
942
+ #define CL_IMPORT_TYPE_ANDROID_HARDWARE_BUFFER_ARM 0x41E2
943
+
944
+ /* Data consistency with host property */
945
+ #define CL_IMPORT_DMA_BUF_DATA_CONSISTENCY_WITH_HOST_ARM 0x41E3
946
+
947
+ /* Import memory size value to indicate a size for the whole buffer */
948
+ #define CL_IMPORT_MEMORY_WHOLE_ALLOCATION_ARM SIZE_MAX
949
+
950
+ /* This extension adds a new function that allows for direct memory import into
951
+ * OpenCL via the clImportMemoryARM function.
952
+ *
953
+ * Memory imported through this interface will be mapped into the device's page
954
+ * tables directly, providing zero copy access. It will never fall back to copy
955
+ * operations and aliased buffers.
956
+ *
957
+ * Types of memory supported for import are specified as additional extension
958
+ * strings.
959
+ *
960
+ * This extension produces cl_mem allocations which are compatible with all other
961
+ * users of cl_mem in the standard API.
962
+ *
963
+ * This extension maps pages with the same properties as the normal buffer creation
964
+ * function clCreateBuffer.
965
+ */
966
+ extern CL_API_ENTRY cl_mem CL_API_CALL
967
+ clImportMemoryARM( cl_context context,
968
+ cl_mem_flags flags,
969
+ const cl_import_properties_arm *properties,
970
+ void *memory,
971
+ size_t size,
972
+ cl_int *errcode_ret) CL_EXT_SUFFIX__VERSION_1_0;
973
+
974
+
975
+ /******************************************
976
+ * cl_arm_shared_virtual_memory extension *
977
+ ******************************************/
978
+ #define cl_arm_shared_virtual_memory 1
979
+
980
+ /* Used by clGetDeviceInfo */
981
+ #define CL_DEVICE_SVM_CAPABILITIES_ARM 0x40B6
982
+
983
+ /* Used by clGetMemObjectInfo */
984
+ #define CL_MEM_USES_SVM_POINTER_ARM 0x40B7
985
+
986
+ /* Used by clSetKernelExecInfoARM: */
987
+ #define CL_KERNEL_EXEC_INFO_SVM_PTRS_ARM 0x40B8
988
+ #define CL_KERNEL_EXEC_INFO_SVM_FINE_GRAIN_SYSTEM_ARM 0x40B9
989
+
990
+ /* To be used by clGetEventInfo: */
991
+ #define CL_COMMAND_SVM_FREE_ARM 0x40BA
992
+ #define CL_COMMAND_SVM_MEMCPY_ARM 0x40BB
993
+ #define CL_COMMAND_SVM_MEMFILL_ARM 0x40BC
994
+ #define CL_COMMAND_SVM_MAP_ARM 0x40BD
995
+ #define CL_COMMAND_SVM_UNMAP_ARM 0x40BE
996
+
997
+ /* Flag values returned by clGetDeviceInfo with CL_DEVICE_SVM_CAPABILITIES_ARM as the param_name. */
998
+ #define CL_DEVICE_SVM_COARSE_GRAIN_BUFFER_ARM (1 << 0)
999
+ #define CL_DEVICE_SVM_FINE_GRAIN_BUFFER_ARM (1 << 1)
1000
+ #define CL_DEVICE_SVM_FINE_GRAIN_SYSTEM_ARM (1 << 2)
1001
+ #define CL_DEVICE_SVM_ATOMICS_ARM (1 << 3)
1002
+
1003
+ /* Flag values used by clSVMAllocARM: */
1004
+ #define CL_MEM_SVM_FINE_GRAIN_BUFFER_ARM (1 << 10)
1005
+ #define CL_MEM_SVM_ATOMICS_ARM (1 << 11)
1006
+
1007
+ typedef cl_bitfield cl_svm_mem_flags_arm;
1008
+ typedef cl_uint cl_kernel_exec_info_arm;
1009
+ typedef cl_bitfield cl_device_svm_capabilities_arm;
1010
+
1011
+ extern CL_API_ENTRY void * CL_API_CALL
1012
+ clSVMAllocARM(cl_context context,
1013
+ cl_svm_mem_flags_arm flags,
1014
+ size_t size,
1015
+ cl_uint alignment) CL_EXT_SUFFIX__VERSION_1_2;
1016
+
1017
+ extern CL_API_ENTRY void CL_API_CALL
1018
+ clSVMFreeARM(cl_context context,
1019
+ void * svm_pointer) CL_EXT_SUFFIX__VERSION_1_2;
1020
+
1021
+ extern CL_API_ENTRY cl_int CL_API_CALL
1022
+ clEnqueueSVMFreeARM(cl_command_queue command_queue,
1023
+ cl_uint num_svm_pointers,
1024
+ void * svm_pointers[],
1025
+ void (CL_CALLBACK * pfn_free_func)(cl_command_queue queue,
1026
+ cl_uint num_svm_pointers,
1027
+ void * svm_pointers[],
1028
+ void * user_data),
1029
+ void * user_data,
1030
+ cl_uint num_events_in_wait_list,
1031
+ const cl_event * event_wait_list,
1032
+ cl_event * event) CL_EXT_SUFFIX__VERSION_1_2;
1033
+
1034
+ extern CL_API_ENTRY cl_int CL_API_CALL
1035
+ clEnqueueSVMMemcpyARM(cl_command_queue command_queue,
1036
+ cl_bool blocking_copy,
1037
+ void * dst_ptr,
1038
+ const void * src_ptr,
1039
+ size_t size,
1040
+ cl_uint num_events_in_wait_list,
1041
+ const cl_event * event_wait_list,
1042
+ cl_event * event) CL_EXT_SUFFIX__VERSION_1_2;
1043
+
1044
+ extern CL_API_ENTRY cl_int CL_API_CALL
1045
+ clEnqueueSVMMemFillARM(cl_command_queue command_queue,
1046
+ void * svm_ptr,
1047
+ const void * pattern,
1048
+ size_t pattern_size,
1049
+ size_t size,
1050
+ cl_uint num_events_in_wait_list,
1051
+ const cl_event * event_wait_list,
1052
+ cl_event * event) CL_EXT_SUFFIX__VERSION_1_2;
1053
+
1054
+ extern CL_API_ENTRY cl_int CL_API_CALL
1055
+ clEnqueueSVMMapARM(cl_command_queue command_queue,
1056
+ cl_bool blocking_map,
1057
+ cl_map_flags flags,
1058
+ void * svm_ptr,
1059
+ size_t size,
1060
+ cl_uint num_events_in_wait_list,
1061
+ const cl_event * event_wait_list,
1062
+ cl_event * event) CL_EXT_SUFFIX__VERSION_1_2;
1063
+
1064
+ extern CL_API_ENTRY cl_int CL_API_CALL
1065
+ clEnqueueSVMUnmapARM(cl_command_queue command_queue,
1066
+ void * svm_ptr,
1067
+ cl_uint num_events_in_wait_list,
1068
+ const cl_event * event_wait_list,
1069
+ cl_event * event) CL_EXT_SUFFIX__VERSION_1_2;
1070
+
1071
+ extern CL_API_ENTRY cl_int CL_API_CALL
1072
+ clSetKernelArgSVMPointerARM(cl_kernel kernel,
1073
+ cl_uint arg_index,
1074
+ const void * arg_value) CL_EXT_SUFFIX__VERSION_1_2;
1075
+
1076
+ extern CL_API_ENTRY cl_int CL_API_CALL
1077
+ clSetKernelExecInfoARM(cl_kernel kernel,
1078
+ cl_kernel_exec_info_arm param_name,
1079
+ size_t param_value_size,
1080
+ const void * param_value) CL_EXT_SUFFIX__VERSION_1_2;
1081
+
1082
+ /********************************
1083
+ * cl_arm_get_core_id extension *
1084
+ ********************************/
1085
+
1086
+ #ifdef CL_VERSION_1_2
1087
+
1088
+ #define cl_arm_get_core_id 1
1089
+
1090
+ /* Device info property for bitfield of cores present */
1091
+ #define CL_DEVICE_COMPUTE_UNITS_BITFIELD_ARM 0x40BF
1092
+
1093
+ #endif /* CL_VERSION_1_2 */
1094
+
1095
+ /*********************************
1096
+ * cl_arm_job_slot_selection
1097
+ *********************************/
1098
+
1099
+ #define cl_arm_job_slot_selection 1
1100
+
1101
+ /* cl_device_info */
1102
+ #define CL_DEVICE_JOB_SLOTS_ARM 0x41E0
1103
+
1104
+ /* cl_command_queue_properties */
1105
+ #define CL_QUEUE_JOB_SLOT_ARM 0x41E1
1106
+
1107
+ /*********************************
1108
+ * cl_arm_scheduling_controls
1109
+ *********************************/
1110
+
1111
+ #define cl_arm_scheduling_controls 1
1112
+
1113
+ /* cl_device_info */
1114
+ #define CL_DEVICE_SCHEDULING_CONTROLS_CAPABILITIES_ARM 0x41E4
1115
+
1116
+ #define CL_DEVICE_SCHEDULING_KERNEL_BATCHING_ARM (1 << 0)
1117
+ #define CL_DEVICE_SCHEDULING_WORKGROUP_BATCH_SIZE_ARM (1 << 1)
1118
+ #define CL_DEVICE_SCHEDULING_WORKGROUP_BATCH_SIZE_MODIFIER_ARM (1 << 2)
1119
+
1120
+ /* cl_kernel_info */
1121
+ #define CL_KERNEL_EXEC_INFO_WORKGROUP_BATCH_SIZE_ARM 0x41E5
1122
+ #define CL_KERNEL_EXEC_INFO_WORKGROUP_BATCH_SIZE_MODIFIER_ARM 0x41E6
1123
+
1124
+ /* cl_queue_properties */
1125
+ #define CL_QUEUE_KERNEL_BATCHING_ARM 0x41E7
1126
+
1127
+ #ifdef __cplusplus
1128
+ }
1129
+ #endif
1130
+
1131
+ #endif /* __CL_EXT_H */
tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/cooperative_groups/details/async.h ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 1993-2016 NVIDIA Corporation. All rights reserved.
2
+ *
3
+ * NOTICE TO LICENSEE:
4
+ *
5
+ * The source code and/or documentation ("Licensed Deliverables") are
6
+ * subject to NVIDIA intellectual property rights under U.S. and
7
+ * international Copyright laws.
8
+ *
9
+ * The Licensed Deliverables contained herein are PROPRIETARY and
10
+ * CONFIDENTIAL to NVIDIA and are being provided under the terms and
11
+ * conditions of a form of NVIDIA software license agreement by and
12
+ * between NVIDIA and Licensee ("License Agreement") or electronically
13
+ * accepted by Licensee. Notwithstanding any terms or conditions to
14
+ * the contrary in the License Agreement, reproduction or disclosure
15
+ * of the Licensed Deliverables to any third party without the express
16
+ * written consent of NVIDIA is prohibited.
17
+ *
18
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
19
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
20
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. THEY ARE
21
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
22
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
23
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
24
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
25
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
26
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
27
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
28
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
30
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
31
+ * OF THESE LICENSED DELIVERABLES.
32
+ *
33
+ * U.S. Government End Users. These Licensed Deliverables are a
34
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
35
+ * 1995), consisting of "commercial computer software" and "commercial
36
+ * computer software documentation" as such terms are used in 48
37
+ * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
38
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
39
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
40
+ * U.S. Government End Users acquire the Licensed Deliverables with
41
+ * only those rights set forth herein.
42
+ *
43
+ * Any use of the Licensed Deliverables in individual and commercial
44
+ * software must include, in the user documentation and internal
45
+ * comments to the code, the above Disclaimer and U.S. Government End
46
+ * Users Notice.
47
+ */
48
+
49
+ #ifndef _CG_ASYNC_H
50
+ #define _CG_ASYNC_H
51
+
52
+ #include "helpers.h"
53
+ #include "info.h"
54
+
55
+ #include <cuda_pipeline.h>
56
+
57
+ _CG_BEGIN_NAMESPACE
58
+
59
+ namespace details {
60
+ // Groups supported by memcpy_async
61
+ template <class TyGroup>
62
+ struct _async_copy_group_supported : public _CG_STL_NAMESPACE::false_type {};
63
+
64
+ template <unsigned int Sz, typename TyPar>
65
+ struct _async_copy_group_supported<cooperative_groups::thread_block_tile<Sz, TyPar>>
66
+ : public _CG_STL_NAMESPACE::true_type {};
67
+ template <>
68
+ struct _async_copy_group_supported<cooperative_groups::coalesced_group> : public _CG_STL_NAMESPACE::true_type {};
69
+ template <>
70
+ struct _async_copy_group_supported<cooperative_groups::thread_block> : public _CG_STL_NAMESPACE::true_type {};
71
+
72
+ template <class TyGroup>
73
+ using async_copy_group_supported = _async_copy_group_supported<details::remove_qual<TyGroup>>;
74
+
75
+ // Groups that require optimization
76
+ template <class TyGroup>
77
+ struct _async_copy_optimize_tile : public _CG_STL_NAMESPACE::false_type {};
78
+
79
+ template <typename TyPar>
80
+ struct _async_copy_optimize_tile<cooperative_groups::thread_block_tile<1, TyPar>>
81
+ : public _CG_STL_NAMESPACE::false_type {};
82
+
83
+ template <unsigned int Sz, typename TyPar>
84
+ struct _async_copy_optimize_tile<cooperative_groups::thread_block_tile<Sz, TyPar>>
85
+ : public _CG_STL_NAMESPACE::true_type {};
86
+
87
+ template <class TyGroup>
88
+ using async_copy_optimize_tile = _async_copy_optimize_tile<details::remove_qual<TyGroup>>;
89
+
90
+ // SFINAE helpers for tile optimizations
91
+ template <class TyGroup>
92
+ using enable_tile_optimization =
93
+ typename _CG_STL_NAMESPACE::enable_if<async_copy_optimize_tile<TyGroup>::value, void *>::type;
94
+
95
+ template <class TyGroup>
96
+ using disable_tile_optimization =
97
+ typename _CG_STL_NAMESPACE::enable_if<!async_copy_optimize_tile<TyGroup>::value, void *>::type;
98
+
99
+ // Segment for punning to aligned types
100
+ template <unsigned int N>
101
+ struct _Segment {
102
+ int _seg[N];
103
+ };
104
+
105
+ // Trivial layout guaranteed-aligned copy-async compatible segments
106
+ template <unsigned int N>
107
+ struct Segment;
108
+ template <>
109
+ struct __align__(4) Segment<1> : public _Segment<1>{};
110
+ template <>
111
+ struct __align__(8) Segment<2> : public _Segment<2>{};
112
+ template <>
113
+ struct __align__(16) Segment<4> : public _Segment<4>{};
114
+
115
+ // Interleaved element by element copies from source to dest
116
+ template <typename TyGroup, typename TyElem>
117
+ _CG_STATIC_QUALIFIER void inline_copy(TyGroup &group, TyElem *__restrict__ dst, const TyElem *__restrict__ src,
118
+ size_t count) {
119
+ const unsigned int rank = group.thread_rank();
120
+ const unsigned int stride = group.size();
121
+
122
+ for (size_t idx = rank; idx < count; idx += stride) {
123
+ dst[idx] = src[idx];
124
+ }
125
+ }
126
+
127
+ template <typename TyGroup, typename TyElem, enable_tile_optimization<TyGroup> = nullptr>
128
+ _CG_STATIC_QUALIFIER void accelerated_async_copy(TyGroup &group, TyElem *__restrict__ dst,
129
+ const TyElem *__restrict__ src, size_t count) {
130
+ static_assert(async_copy_group_supported<TyGroup>::value,
131
+ "Async copy is only supported for groups that represent private shared memory");
132
+
133
+ if (count == 0) {
134
+ return;
135
+ }
136
+
137
+ const bool dstIsNotShared = !__isShared(dst);
138
+ const bool srcIsNotGlobal = !__isGlobal(src);
139
+
140
+ if (dstIsNotShared || srcIsNotGlobal) {
141
+ inline_copy(group, dst, src, count);
142
+ return;
143
+ }
144
+
145
+ const unsigned int stride = group.size();
146
+ const unsigned int rank = group.thread_rank();
147
+ // Efficient copies require warps to operate on the same amount of work at each step.
148
+ // remainders are handled in a separate stage to prevent branching
149
+ const unsigned int subWarpMask = (stride - 1);
150
+ const unsigned int subwarpCopies = (subWarpMask & (unsigned int)count);
151
+ const unsigned int maxSubwarpRank = min(rank, subwarpCopies - 1);
152
+
153
+ const size_t warpCopies = (count & (~subWarpMask));
154
+
155
+ for (size_t idx = 0; idx < warpCopies; idx += stride) {
156
+ size_t _srcIdx = rank + idx;
157
+ size_t _dstIdx = rank + idx;
158
+ __pipeline_memcpy_async(dst + _dstIdx, src + _srcIdx, sizeof(TyElem));
159
+ }
160
+
161
+ if (subwarpCopies) {
162
+ size_t _srcIdx = warpCopies + maxSubwarpRank;
163
+ size_t _dstIdx = warpCopies + maxSubwarpRank;
164
+ __pipeline_memcpy_async(dst + _dstIdx, src + _srcIdx, sizeof(TyElem));
165
+ }
166
+ }
167
+
168
+ template <typename TyGroup, typename TyElem, disable_tile_optimization<TyGroup> = nullptr>
169
+ _CG_STATIC_QUALIFIER void accelerated_async_copy(TyGroup &group, TyElem *__restrict__ dst,
170
+ const TyElem *__restrict__ src, size_t count) {
171
+ static_assert(async_copy_group_supported<TyGroup>::value,
172
+ "Async copy is only supported for groups that represent private shared memory");
173
+
174
+ const bool dstIsNotShared = !__isShared(dst);
175
+ const bool srcIsNotGlobal = !__isGlobal(src);
176
+
177
+ if (dstIsNotShared || srcIsNotGlobal) {
178
+ inline_copy(group, dst, src, count);
179
+ return;
180
+ }
181
+
182
+ unsigned int stride = group.size();
183
+ unsigned int rank = group.thread_rank();
184
+
185
+ for (size_t idx = rank; idx < count; idx += stride) {
186
+ size_t _srcIdx = idx;
187
+ size_t _dstIdx = idx;
188
+ __pipeline_memcpy_async(dst + _dstIdx, src + _srcIdx, sizeof(TyElem));
189
+ }
190
+ }
191
+
192
+ // Determine best possible alignment given an input and initial conditions
193
+ // Attempts to generate as little code as possible, most likely should only be used with 1 and 2 byte alignments
194
+ template <unsigned int MinAlignment, unsigned int MaxAlignment>
195
+ _CG_STATIC_QUALIFIER uint32_t find_best_alignment(void *__restrict__ dst, const void *__restrict__ src) {
196
+ // Narrowing conversion intentional
197
+ uint32_t base1 = (uint32_t) reinterpret_cast<uintptr_t>(src);
198
+ uint32_t base2 = (uint32_t) reinterpret_cast<uintptr_t>(dst);
199
+
200
+ uint32_t diff = ((base1) ^ (base2)) & (MaxAlignment - 1);
201
+
202
+ // range [MaxAlignment, alignof(elem)], step: x >> 1
203
+ // over range of possible alignments, choose best available out of range
204
+ uint32_t out = MaxAlignment;
205
+ #pragma unroll
206
+ for (uint32_t alignment = (MaxAlignment >> 1); alignment >= MinAlignment; alignment >>= 1) {
207
+ if (alignment & diff)
208
+ out = alignment;
209
+ }
210
+
211
+ return out;
212
+ }
213
+
214
+ // Determine best possible alignment given an input and initial conditions
215
+ // Attempts to generate as little code as possible, most likely should only be used with 1 and 2 byte alignments
216
+ template <typename TyType, typename TyGroup>
217
+ _CG_STATIC_QUALIFIER void copy_like(const TyGroup &group, void *__restrict__ _dst, const void *__restrict__ _src,
218
+ size_t count) {
219
+ const char *src = reinterpret_cast<const char *>(_src);
220
+ char *dst = reinterpret_cast<char *>(_dst);
221
+
222
+ constexpr uint32_t targetAlignment = (uint32_t)alignof(TyType);
223
+
224
+ uint32_t base = (uint32_t) reinterpret_cast<uintptr_t>(src);
225
+ uint32_t alignOffset = ((~base) + 1) & (targetAlignment - 1);
226
+
227
+ inline_copy(group, dst, src, alignOffset);
228
+ count -= alignOffset;
229
+ src += alignOffset;
230
+ dst += alignOffset;
231
+
232
+ // Copy using the best available alignment, async_copy expects n-datums, not bytes
233
+ size_t asyncCount = count / sizeof(TyType);
234
+ accelerated_async_copy(group, reinterpret_cast<TyType *>(dst), reinterpret_cast<const TyType *>(src), asyncCount);
235
+ asyncCount *= sizeof(TyType);
236
+
237
+ count -= asyncCount;
238
+ src += asyncCount;
239
+ dst += asyncCount;
240
+ inline_copy(group, dst, src, count);
241
+ }
242
+
243
+ // We must determine alignment and manually align src/dst ourselves
244
+ template <size_t AlignHint>
245
+ struct _memcpy_async_align_dispatch {
246
+ template <typename TyGroup>
247
+ _CG_STATIC_QUALIFIER void copy(TyGroup &group, void *__restrict__ dst, const void *__restrict__ src, size_t count) {
248
+ uint32_t alignment = find_best_alignment<AlignHint, 16>(dst, src);
249
+
250
+ // Avoid copying the extra bytes if desired copy count is smaller
251
+ alignment = count < alignment ? AlignHint : alignment;
252
+
253
+ switch (alignment) {
254
+ default:
255
+ case 1:
256
+ inline_copy(group, reinterpret_cast<char *>(dst), reinterpret_cast<const char *>(src), count);
257
+ break;
258
+ case 2:
259
+ inline_copy(group, reinterpret_cast<short *>(dst), reinterpret_cast<const short *>(src), count >> 1);
260
+ break;
261
+ case 4:
262
+ copy_like<Segment<1>>(group, dst, src, count);
263
+ break;
264
+ case 8:
265
+ copy_like<Segment<2>>(group, dst, src, count);
266
+ break;
267
+ case 16:
268
+ copy_like<Segment<4>>(group, dst, src, count);
269
+ break;
270
+ }
271
+ }
272
+ };
273
+
274
+ // Specialization for 4 byte alignments
275
+ template <>
276
+ struct _memcpy_async_align_dispatch<4> {
277
+ template <typename TyGroup>
278
+ _CG_STATIC_QUALIFIER void copy(TyGroup &group, void *__restrict__ _dst, const void *__restrict__ _src,
279
+ size_t count) {
280
+ const Segment<1> *src = reinterpret_cast<const Segment<1> *>(_src);
281
+ Segment<1> *dst = reinterpret_cast<Segment<1> *>(_dst);
282
+
283
+ // Dispatch straight to aligned LDGSTS calls
284
+ accelerated_async_copy(group, dst, src, count / sizeof(*dst));
285
+ }
286
+ };
287
+
288
+ // Specialization for 8 byte alignments
289
+ template <>
290
+ struct _memcpy_async_align_dispatch<8> {
291
+ template <typename TyGroup>
292
+ _CG_STATIC_QUALIFIER void copy(TyGroup &group, void *__restrict__ _dst, const void *__restrict__ _src,
293
+ size_t count) {
294
+ const Segment<2> *src = reinterpret_cast<const Segment<2> *>(_src);
295
+ Segment<2> *dst = reinterpret_cast<Segment<2> *>(_dst);
296
+
297
+ // Dispatch straight to aligned LDGSTS calls
298
+ accelerated_async_copy(group, dst, src, count / sizeof(*dst));
299
+ }
300
+ };
301
+
302
+ // Alignments over 16 are truncated to 16 and bypass alignment
303
+ // This is the highest performing memcpy available
304
+ template <>
305
+ struct _memcpy_async_align_dispatch<16> {
306
+ template <typename TyGroup>
307
+ _CG_STATIC_QUALIFIER void copy(TyGroup &group, void *__restrict__ _dst, const void *__restrict__ _src,
308
+ size_t count) {
309
+ const Segment<4> *src = reinterpret_cast<const Segment<4> *>(_src);
310
+ Segment<4> *dst = reinterpret_cast<Segment<4> *>(_dst);
311
+
312
+ // Dispatch straight to aligned LDGSTS calls
313
+ accelerated_async_copy(group, dst, src, count / sizeof(*dst));
314
+ }
315
+ };
316
+
317
+ // byte-wide API
318
+ template <size_t Alignment, class TyGroup>
319
+ _CG_STATIC_QUALIFIER void _memcpy_async_dispatch_to_aligned_copy(const TyGroup &group, void *__restrict__ _dst,
320
+ const void *__restrict__ _src, size_t count) {
321
+ static_assert(!(Alignment & (Alignment - 1)), "Known static alignment dispatch must be a power of 2");
322
+ details::_memcpy_async_align_dispatch<Alignment>::copy(group, _dst, _src, count);
323
+ }
324
+
325
+ // Internal dispatch APIs
326
+ // These deduce the alignments and sizes necessary to invoke the underlying copy engine
327
+ template <typename Ty>
328
+ using is_void = _CG_STL_NAMESPACE::is_same<Ty, void>;
329
+
330
+ template <typename Ty>
331
+ using enable_if_not_void = typename _CG_STL_NAMESPACE::enable_if<!is_void<Ty>::value, void *>::type;
332
+
333
+ template <typename Ty>
334
+ using enable_if_void = typename _CG_STL_NAMESPACE::enable_if<is_void<Ty>::value, void *>::type;
335
+
336
+ template <typename Ty>
337
+ using enable_if_integral =
338
+ typename _CG_STL_NAMESPACE::enable_if<_CG_STL_NAMESPACE::is_integral<Ty>::value, void *>::type;
339
+
340
+ // byte-wide API using aligned_sized_t
341
+ template <class TyGroup, template <size_t> typename Alignment, size_t Hint>
342
+ _CG_STATIC_QUALIFIER void _memcpy_async_bytes(const TyGroup &group, void *__restrict__ _dst,
343
+ const void *__restrict__ _src, const Alignment<Hint> &count) {
344
+ constexpr size_t _align = (Hint > 16) ? 16 : Hint;
345
+
346
+ details::_memcpy_async_dispatch_to_aligned_copy<_align>(group, _dst, _src, (size_t)count);
347
+ }
348
+
349
+ // byte-wide API using type for aligment
350
+ template <class TyGroup, typename TyElem, typename TySize, size_t Hint = alignof(TyElem),
351
+ enable_if_not_void<TyElem> = nullptr, enable_if_integral<TySize> = nullptr>
352
+ _CG_STATIC_QUALIFIER void _memcpy_async_bytes(const TyGroup &group, TyElem *__restrict__ _dst,
353
+ const TyElem *__restrict__ _src, const TySize& count) {
354
+ constexpr size_t _align = (Hint > 16) ? 16 : Hint;
355
+
356
+ details::_memcpy_async_dispatch_to_aligned_copy<_align>(group, _dst, _src, count);
357
+ }
358
+
359
+ // byte-wide API with full alignment deduction required
360
+ template <class TyGroup, typename TyElem, typename TySize, enable_if_void<TyElem> = nullptr,
361
+ enable_if_integral<TySize> = nullptr>
362
+ _CG_STATIC_QUALIFIER void _memcpy_async_bytes(const TyGroup &group, TyElem *__restrict__ _dst,
363
+ const TyElem *__restrict__ _src, const TySize& count) {
364
+ details::_memcpy_async_dispatch_to_aligned_copy<1>(group, _dst, _src, count);
365
+ }
366
+
367
+ // 1d-datum API
368
+ template <class TyGroup, typename TyElem, size_t Hint = alignof(TyElem)>
369
+ _CG_STATIC_QUALIFIER void _memcpy_async_datum(const TyGroup &group, TyElem *__restrict__ dst, const size_t dstCount,
370
+ const TyElem *__restrict__ src, const size_t srcCount) {
371
+ constexpr unsigned int _align = Hint;
372
+ const size_t totalCount = min(dstCount, srcCount) * sizeof(TyElem);
373
+
374
+ details::_memcpy_async_dispatch_to_aligned_copy<_align>(group, dst, src, totalCount);
375
+ }
376
+
377
+ // 1d-datum API using aligned_size_t
378
+ template <class TyGroup, typename TyElem, template <size_t> typename Alignment, size_t Hint>
379
+ _CG_STATIC_QUALIFIER void _memcpy_async_datum(const TyGroup &group, TyElem *__restrict__ dst, const Alignment<Hint> &dstCount,
380
+ const TyElem *__restrict__ src, const Alignment<Hint> &srcCount) {
381
+ constexpr unsigned int _align = Hint;
382
+ const size_t totalCount = min((size_t)dstCount, (size_t)srcCount) * sizeof(TyElem);
383
+
384
+ details::_memcpy_async_dispatch_to_aligned_copy<_align>(group, dst, src, totalCount);
385
+ }
386
+
387
+ } // namespace details
388
+
389
+ /*
390
+ * Group submit batch of async-copy to cover contiguous 1D array
391
+ * and commit that batch to eventually wait for completion.
392
+ */
393
+ template <class TyGroup, typename TyElem, typename TySizeT>
394
+ _CG_STATIC_QUALIFIER void memcpy_async(const TyGroup &group, TyElem *__restrict__ _dst, const TyElem *__restrict__ _src,
395
+ const TySizeT &count) {
396
+ details::_memcpy_async_bytes(group, _dst, _src, count);
397
+ __pipeline_commit();
398
+ }
399
+
400
+ /*
401
+ * Group submit batch of async-copy to cover contiguous 1D array
402
+ * and commit that batch to eventually wait for completion.
403
+ * Object counts are in datum sized chunks, not bytes.
404
+ */
405
+ template <class TyGroup, class TyElem, typename DstLayout, typename SrcLayout>
406
+ _CG_STATIC_QUALIFIER void memcpy_async(const TyGroup &group, TyElem *__restrict__ dst, const DstLayout &dstLayout,
407
+ const TyElem *__restrict__ src, const SrcLayout &srcLayout) {
408
+ details::_memcpy_async_datum(group, dst, dstLayout, src, srcLayout);
409
+ __pipeline_commit();
410
+ }
411
+
412
+ /* Group wait for prior Nth stage of memcpy_async to complete. */
413
+ template <unsigned int Stage, class TyGroup>
414
+ _CG_STATIC_QUALIFIER void wait_prior(const TyGroup &group) {
415
+ __pipeline_wait_prior(Stage);
416
+ group.sync();
417
+ }
418
+
419
+ /* Group wait all previously submitted memcpy_async to complete. */
420
+ template <class TyGroup>
421
+ _CG_STATIC_QUALIFIER void wait(const TyGroup &group) {
422
+ __pipeline_wait_prior(0);
423
+ group.sync();
424
+ }
425
+
426
+ /***************** CG APIs including pipeline are deprecated *****************/
427
+
428
+ /* Group submit batch of async-copy to cover of contiguous 1D array
429
+ to a pipeline and commit the batch*/
430
+ template <class TyGroup, class TyElem>
431
+ _CG_DEPRECATED _CG_STATIC_QUALIFIER void memcpy_async(TyGroup &group, TyElem *dst, size_t dstCount, const TyElem *src, size_t srcCount,
432
+ nvcuda::experimental::pipeline &pipe) {
433
+ details::_memcpy_async_datum(group, dst, dstCount, src, srcCount);
434
+ pipe.commit();
435
+ }
436
+
437
+ /* Group wait for prior Nth stage of memcpy_async to complete. */
438
+ template <unsigned int Stage, class TyGroup>
439
+ _CG_DEPRECATED _CG_STATIC_QUALIFIER void wait_prior(TyGroup &group, nvcuda::experimental::pipeline &pipe) {
440
+ pipe.wait_prior<Stage>();
441
+ group.sync();
442
+ }
443
+
444
+ /* Group wait for stage-S of memcpy_async to complete. */
445
+ template <class TyGroup>
446
+ _CG_DEPRECATED _CG_STATIC_QUALIFIER void wait(TyGroup &group, nvcuda::experimental::pipeline &pipe, size_t stage) {
447
+ pipe.wait(stage);
448
+ group.sync();
449
+ }
450
+ _CG_END_NAMESPACE
451
+
452
+ #endif // _CG_ASYNC_H
tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/cooperative_groups/details/coalesced_scan.h ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 1993-2016 NVIDIA Corporation. All rights reserved.
2
+ *
3
+ * NOTICE TO LICENSEE:
4
+ *
5
+ * The source code and/or documentation ("Licensed Deliverables") are
6
+ * subject to NVIDIA intellectual property rights under U.S. and
7
+ * international Copyright laws.
8
+ *
9
+ * The Licensed Deliverables contained herein are PROPRIETARY and
10
+ * CONFIDENTIAL to NVIDIA and are being provided under the terms and
11
+ * conditions of a form of NVIDIA software license agreement by and
12
+ * between NVIDIA and Licensee ("License Agreement") or electronically
13
+ * accepted by Licensee. Notwithstanding any terms or conditions to
14
+ * the contrary in the License Agreement, reproduction or disclosure
15
+ * of the Licensed Deliverables to any third party without the express
16
+ * written consent of NVIDIA is prohibited.
17
+ *
18
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
19
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
20
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. THEY ARE
21
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
22
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
23
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
24
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
25
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
26
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
27
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
28
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
30
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
31
+ * OF THESE LICENSED DELIVERABLES.
32
+ *
33
+ * U.S. Government End Users. These Licensed Deliverables are a
34
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
35
+ * 1995), consisting of "commercial computer software" and "commercial
36
+ * computer software documentation" as such terms are used in 48
37
+ * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
38
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
39
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
40
+ * U.S. Government End Users acquire the Licensed Deliverables with
41
+ * only those rights set forth herein.
42
+ *
43
+ * Any use of the Licensed Deliverables in individual and commercial
44
+ * software must include, in the user documentation and internal
45
+ * comments to the code, the above Disclaimer and U.S. Government End
46
+ * Users Notice.
47
+ */
48
+
49
+ #ifndef _CG_COALESCED_SCAN_H_
50
+ #define _CG_COALESCED_SCAN_H_
51
+
52
+ #include "info.h"
53
+ #include "helpers.h"
54
+ #include "cooperative_groups.h"
55
+ #include "partitioning.h"
56
+ #include "functional.h"
57
+
58
+ _CG_BEGIN_NAMESPACE
59
+
60
+ namespace details {
61
+
62
+ template <typename TyGroup, typename TyVal, typename TyOp>
63
+ _CG_QUALIFIER auto inclusive_scan_contiguous(const TyGroup& group, TyVal&& val, TyOp&& op) -> decltype(op(val, val)) {
64
+ auto out = val;
65
+ for (int mask = 1; mask < group.size(); mask <<= 1) {
66
+ auto tmp = group.shfl_up(out, mask);
67
+ if (mask <= group.thread_rank()) {
68
+ out = op(out, tmp);
69
+ }
70
+ }
71
+
72
+ return out;
73
+ }
74
+
75
+ template <typename TyGroup, typename TyVal, typename TyOp>
76
+ _CG_QUALIFIER auto inclusive_scan_non_contiguous(const TyGroup& group, TyVal&& val, TyOp&& op) -> decltype(op(val, val)) {
77
+ const unsigned int groupSize = group.size();
78
+ auto out = val;
79
+
80
+ const unsigned int mask = details::_coalesced_group_data_access::get_mask(group);
81
+ unsigned int lanemask = details::lanemask32_lt() & mask;
82
+ unsigned int srcLane = details::laneid();
83
+
84
+ const unsigned int base = __ffs(mask)-1; /* lane with rank == 0 */
85
+ const unsigned int rank = __popc(lanemask);
86
+
87
+ for (unsigned int i = 1, j = 1; i < groupSize; i <<= 1) {
88
+ if (i <= rank) {
89
+ srcLane -= j;
90
+ j = i; /* maximum possible lane */
91
+
92
+ unsigned int begLane = base + rank - i; /* minimum possible lane */
93
+
94
+ /* Next source lane is in the range [ begLane .. srcLane ]
95
+ * If begLane < srcLane then do a binary search.
96
+ */
97
+ while (begLane < srcLane) {
98
+ const unsigned int halfLane = (begLane + srcLane) >> 1;
99
+ const unsigned int halfMask = lanemask >> halfLane;
100
+ const unsigned int d = __popc(halfMask);
101
+ if (d < i) {
102
+ srcLane = halfLane - 1; /* halfLane too large */
103
+ }
104
+ else if ((i < d) || !(halfMask & 0x01)) {
105
+ begLane = halfLane + 1; /* halfLane too small */
106
+ }
107
+ else {
108
+ begLane = srcLane = halfLane; /* happen to hit */
109
+ }
110
+ }
111
+ }
112
+
113
+ auto tmp = details::tile::shuffle_dispatch<TyVal>::shfl(out, mask, srcLane, 32);
114
+ if (i <= rank) {
115
+ out = op(out, tmp);
116
+ }
117
+ }
118
+ return out;
119
+ }
120
+
121
+ template <unsigned int TySize, typename ParentT, typename TyVal, typename TyOp>
122
+ _CG_QUALIFIER auto coalesced_inclusive_scan(const __single_warp_thread_block_tile<TySize, ParentT>& group,
123
+ TyVal&& val,
124
+ TyOp&& op) -> decltype(op(val, val)) {
125
+ return inclusive_scan_contiguous(group, _CG_STL_NAMESPACE::forward<TyVal>(val), _CG_STL_NAMESPACE::forward<TyOp>(op));
126
+ }
127
+
128
+ template <typename TyVal, typename TyOp>
129
+ _CG_QUALIFIER auto coalesced_inclusive_scan(const coalesced_group& group, TyVal&& val, TyOp&& op) -> decltype(op(val, val)) {
130
+ if (group.size() == 32) {
131
+ return inclusive_scan_contiguous(group, _CG_STL_NAMESPACE::forward<TyVal>(val), _CG_STL_NAMESPACE::forward<TyOp>(op));
132
+ }
133
+ else {
134
+ return inclusive_scan_non_contiguous(group, _CG_STL_NAMESPACE::forward<TyVal>(val), _CG_STL_NAMESPACE::forward<TyOp>(op));
135
+ }
136
+ }
137
+
138
+ template <bool IntegralOptimized>
139
+ struct scan_choose_convertion;
140
+
141
+ template<>
142
+ struct scan_choose_convertion<true> {
143
+ template <typename TyGroup, typename TyRes, typename TyVal>
144
+ _CG_STATIC_QUALIFIER details::remove_qual<TyVal> convert_inclusive_to_exclusive(const TyGroup& group, TyRes& result, TyVal&& val) {
145
+ return result - val;
146
+ }
147
+ };
148
+
149
+ template<>
150
+ struct scan_choose_convertion<false> {
151
+ template <typename TyGroup, typename TyRes, typename TyVal>
152
+ _CG_STATIC_QUALIFIER details::remove_qual<TyVal> convert_inclusive_to_exclusive(const TyGroup& group, TyRes& result, TyVal&& val) {
153
+ auto ret = group.shfl_up(result, 1);
154
+ if (group.thread_rank() == 0) {
155
+ return {};
156
+ }
157
+ else {
158
+ return ret;
159
+ }
160
+ }
161
+ };
162
+
163
+ template <typename TyGroup, typename TyRes, typename TyVal, typename TyFn>
164
+ _CG_QUALIFIER auto convert_inclusive_to_exclusive(const TyGroup& group, TyRes& result, TyVal&& val, TyFn&& op) -> decltype(op(val, val)) {
165
+ using conversion = scan_choose_convertion<_CG_STL_NAMESPACE::is_same<remove_qual<TyFn>, cooperative_groups::plus<remove_qual<TyVal>>>::value
166
+ && _CG_STL_NAMESPACE::is_integral<remove_qual<TyVal>>::value>;
167
+ return conversion::convert_inclusive_to_exclusive(group, result, _CG_STL_NAMESPACE::forward<TyVal>(val));
168
+ }
169
+
170
+ } // details
171
+
172
+ _CG_END_NAMESPACE
173
+
174
+ #endif // _CG_COALESCED_SCAN_H_
tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/cooperative_groups/details/driver_abi.h ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 1993-2016 NVIDIA Corporation. All rights reserved.
2
+ *
3
+ * NOTICE TO LICENSEE:
4
+ *
5
+ * The source code and/or documentation ("Licensed Deliverables") are
6
+ * subject to NVIDIA intellectual property rights under U.S. and
7
+ * international Copyright laws.
8
+ *
9
+ * The Licensed Deliverables contained herein are PROPRIETARY and
10
+ * CONFIDENTIAL to NVIDIA and are being provided under the terms and
11
+ * conditions of a form of NVIDIA software license agreement by and
12
+ * between NVIDIA and Licensee ("License Agreement") or electronically
13
+ * accepted by Licensee. Notwithstanding any terms or conditions to
14
+ * the contrary in the License Agreement, reproduction or disclosure
15
+ * of the Licensed Deliverables to any third party without the express
16
+ * written consent of NVIDIA is prohibited.
17
+ *
18
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
19
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
20
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. THEY ARE
21
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
22
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
23
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
24
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
25
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
26
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
27
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
28
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
30
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
31
+ * OF THESE LICENSED DELIVERABLES.
32
+ *
33
+ * U.S. Government End Users. These Licensed Deliverables are a
34
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
35
+ * 1995), consisting of "commercial computer software" and "commercial
36
+ * computer software documentation" as such terms are used in 48
37
+ * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
38
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
39
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
40
+ * U.S. Government End Users acquire the Licensed Deliverables with
41
+ * only those rights set forth herein.
42
+ *
43
+ * Any use of the Licensed Deliverables in individual and commercial
44
+ * software must include, in the user documentation and internal
45
+ * comments to the code, the above Disclaimer and U.S. Government End
46
+ * Users Notice.
47
+ */
48
+
49
+ #ifndef _CG_DRIVER_API_H
50
+ #define _CG_DRIVER_API_H
51
+
52
+ #include "info.h"
53
+
54
+ _CG_BEGIN_NAMESPACE
55
+
56
+ namespace details {
57
+ template <unsigned int RegId>
58
+ _CG_QUALIFIER unsigned int load_env_reg() {
59
+ // Abort by default
60
+ _CG_ABORT();
61
+ return 0;
62
+ }
63
+
64
+ template <unsigned int HiReg, unsigned int LoReg>
65
+ _CG_QUALIFIER unsigned long long load_env_reg64() {
66
+ unsigned long long registerLo = load_env_reg<LoReg>();
67
+ unsigned long long registerHi = load_env_reg<HiReg>();
68
+
69
+ return (registerHi << 32) | registerLo;
70
+ }
71
+
72
+ // inline PTX for accessing registers requires an immediate for the special reg
73
+ # define LOAD_ENVREG(NUMBER) \
74
+ template <> _CG_QUALIFIER unsigned int load_env_reg<NUMBER>() { \
75
+ unsigned int r; \
76
+ asm ("mov.u32 %0, %%envreg" #NUMBER ";" : "=r"(r)); \
77
+ return r; \
78
+ }
79
+
80
+ // Instantiate loaders for registers used
81
+ LOAD_ENVREG(0);
82
+ LOAD_ENVREG(1);
83
+ LOAD_ENVREG(2);
84
+ # undef LOAD_ENVREG
85
+
86
+ struct grid_workspace {
87
+ unsigned int wsSize;
88
+ unsigned int barrier;
89
+ };
90
+
91
+ _CG_QUALIFIER grid_workspace* get_grid_workspace() {
92
+ unsigned long long gridWsAbiAddress = load_env_reg64<1, 2>();
93
+ // Interpret the address from envreg 1 and 2 as the driver's grid workspace
94
+ return (reinterpret_cast<grid_workspace*>(gridWsAbiAddress));
95
+ }
96
+ }
97
+ _CG_END_NAMESPACE
98
+
99
+ #endif // _CG_DRIVER_API_H
tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/cooperative_groups/details/sync.h ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 1993-2016 NVIDIA Corporation. All rights reserved.
2
+ *
3
+ * NOTICE TO LICENSEE:
4
+ *
5
+ * The source code and/or documentation ("Licensed Deliverables") are
6
+ * subject to NVIDIA intellectual property rights under U.S. and
7
+ * international Copyright laws.
8
+ *
9
+ * The Licensed Deliverables contained herein are PROPRIETARY and
10
+ * CONFIDENTIAL to NVIDIA and are being provided under the terms and
11
+ * conditions of a form of NVIDIA software license agreement by and
12
+ * between NVIDIA and Licensee ("License Agreement") or electronically
13
+ * accepted by Licensee. Notwithstanding any terms or conditions to
14
+ * the contrary in the License Agreement, reproduction or disclosure
15
+ * of the Licensed Deliverables to any third party without the express
16
+ * written consent of NVIDIA is prohibited.
17
+ *
18
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
19
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
20
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. THEY ARE
21
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
22
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
23
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
24
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
25
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
26
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
27
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
28
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
30
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
31
+ * OF THESE LICENSED DELIVERABLES.
32
+ *
33
+ * U.S. Government End Users. These Licensed Deliverables are a
34
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
35
+ * 1995), consisting of "commercial computer software" and "commercial
36
+ * computer software documentation" as such terms are used in 48
37
+ * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
38
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
39
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
40
+ * U.S. Government End Users acquire the Licensed Deliverables with
41
+ * only those rights set forth herein.
42
+ *
43
+ * Any use of the Licensed Deliverables in individual and commercial
44
+ * software must include, in the user documentation and internal
45
+ * comments to the code, the above Disclaimer and U.S. Government End
46
+ * Users Notice.
47
+ */
48
+
49
+ #ifndef _CG_GRID_H
50
+ #define _CG_GRID_H
51
+
52
+ #include "info.h"
53
+
54
+ _CG_BEGIN_NAMESPACE
55
+
56
+ namespace details
57
+ {
58
+
59
+ typedef unsigned int barrier_t;
60
+
61
+ _CG_STATIC_QUALIFIER bool bar_has_flipped(unsigned int old_arrive, unsigned int current_arrive) {
62
+ return (((old_arrive ^ current_arrive) & 0x80000000) != 0);
63
+ }
64
+
65
+ _CG_STATIC_QUALIFIER void bar_flush(volatile unsigned int *addr) {
66
+ #if __CUDA_ARCH__ < 700
67
+ __threadfence();
68
+ #else
69
+ unsigned int val;
70
+ asm volatile("ld.acquire.gpu.u32 %0,[%1];" : "=r"(val) : _CG_ASM_PTR_CONSTRAINT((unsigned int*)addr) : "memory");
71
+ // Avoids compiler warnings from unused variable val
72
+ (void)(val = val);
73
+ #endif
74
+ }
75
+
76
+ _CG_STATIC_QUALIFIER unsigned int atomic_add(volatile unsigned int *addr, unsigned int val) {
77
+ unsigned int old;
78
+ #if __CUDA_ARCH__ < 700
79
+ old = atomicAdd((unsigned int*)addr, val);
80
+ #else
81
+ asm volatile("atom.add.release.gpu.u32 %0,[%1],%2;" : "=r"(old) : _CG_ASM_PTR_CONSTRAINT((unsigned int*)addr), "r"(val) : "memory");
82
+ #endif
83
+ return old;
84
+ }
85
+
86
+ _CG_STATIC_QUALIFIER void sync_grids(unsigned int expected, volatile barrier_t *arrived) {
87
+ bool cta_master = (threadIdx.x + threadIdx.y + threadIdx.z == 0);
88
+ bool gpu_master = (blockIdx.x + blockIdx.y + blockIdx.z == 0);
89
+
90
+ __syncthreads();
91
+
92
+ if (cta_master) {
93
+ unsigned int nb = 1;
94
+ if (gpu_master) {
95
+ nb = 0x80000000 - (expected - 1);
96
+ }
97
+
98
+ __threadfence();
99
+
100
+ unsigned int oldArrive;
101
+ oldArrive = atomic_add(arrived, nb);
102
+
103
+ while (!bar_has_flipped(oldArrive, *arrived));
104
+
105
+ //flush barrier upon leaving
106
+ bar_flush((unsigned int*)arrived);
107
+ }
108
+
109
+ __syncthreads();
110
+ }
111
+
112
+ /* - Multi warp groups synchronization routines - */
113
+
114
+ // Get synchronization bit mask of my thread_block_tile of size num_warps. Thread ranks 0..31 have the first bit assigned to them,
115
+ // thread ranks 32..63 second etc
116
+ // Bit masks are unique for each group, groups of the same size will have the same number of bits set, but on different positions
117
+ _CG_STATIC_QUALIFIER unsigned int get_group_mask(unsigned int thread_rank, unsigned int num_warps) {
118
+ return num_warps == 32 ? ~0 : ((1 << num_warps) - 1) << (num_warps * (thread_rank / (num_warps * 32)));
119
+ }
120
+
121
+ // Default blocking sync.
122
+ _CG_STATIC_QUALIFIER void sync_warps(volatile barrier_t *arrived, unsigned int thread_rank, unsigned int num_warps) {
123
+ unsigned int warp_id = thread_rank / 32;
124
+ bool warp_master = (thread_rank % 32 == 0);
125
+ unsigned int warp_bit = 1 << warp_id;
126
+ unsigned int group_mask = get_group_mask(thread_rank, num_warps);
127
+
128
+ __syncwarp(0xFFFFFFFF);
129
+
130
+ if (warp_master) {
131
+ unsigned int old = atomicOr((unsigned int *)arrived, warp_bit);
132
+ if (((old | warp_bit) & group_mask) == group_mask) {
133
+ atomicAnd((unsigned int *)arrived, ~group_mask);
134
+ }
135
+ else {
136
+ while(*arrived & warp_bit);
137
+ }
138
+ }
139
+
140
+ __syncwarp(0xFFFFFFFF);
141
+ }
142
+
143
+ // Blocking sync, except the last arriving warp, that releases other warps, returns to do other stuff first.
144
+ // Warp returning true from this function needs to call sync_warps_release.
145
+ _CG_STATIC_QUALIFIER bool sync_warps_last_releases(volatile barrier_t *arrived, unsigned int thread_rank, unsigned int num_warps) {
146
+ unsigned int warp_id = thread_rank / 32;
147
+ bool warp_master = (thread_rank % 32 == 0);
148
+ unsigned int warp_bit = 1 << warp_id;
149
+ unsigned int group_mask = get_group_mask(thread_rank, num_warps);
150
+
151
+ __syncwarp(0xFFFFFFFF);
152
+
153
+ unsigned int old = 0;
154
+ if (warp_master) {
155
+ old = atomicOr((unsigned int *)arrived, warp_bit);
156
+ }
157
+ old = __shfl_sync(0xFFFFFFFF, old, 0);
158
+ if (((old | warp_bit) & group_mask) == group_mask) {
159
+ return true;
160
+ }
161
+ while(*arrived & warp_bit);
162
+
163
+ return false;
164
+ }
165
+
166
+ // Release my group from the barrier.
167
+ _CG_STATIC_QUALIFIER void sync_warps_release(volatile barrier_t *arrived, bool is_master, unsigned int thread_rank, unsigned int num_warps) {
168
+ unsigned int group_mask = get_group_mask(thread_rank, num_warps);
169
+ if (is_master) {
170
+ atomicAnd((unsigned int *)arrived, ~group_mask);
171
+ }
172
+ }
173
+
174
+ // Arrive at my group barrier, but don't block or release the barrier, even if every one arrives.
175
+ // sync_warps_release needs to be called by some warp after this one to reset the barrier.
176
+ _CG_STATIC_QUALIFIER void sync_warps_arrive(volatile barrier_t *arrived, unsigned int thread_rank, unsigned int num_warps) {
177
+ unsigned int warp_id = thread_rank / 32;
178
+ bool warp_master = (thread_rank % 32 == 0);
179
+ unsigned int warp_bit = 1 << warp_id;
180
+ unsigned int group_mask = get_group_mask(thread_rank, num_warps);
181
+
182
+ __syncwarp(0xFFFFFFFF);
183
+
184
+ if (warp_master) {
185
+ unsigned int old = atomicOr((unsigned int *)arrived, warp_bit);
186
+ }
187
+ __syncwarp(0xFFFFFFFF);
188
+ }
189
+
190
+ // Arrive at my group barrier, but don't block. Last arriving warp immediately releases the barrier.
191
+ _CG_STATIC_QUALIFIER void sync_warps_arrive_release(volatile barrier_t *arrived, unsigned int thread_rank, unsigned int num_warps) {
192
+ unsigned int warp_id = thread_rank / 32;
193
+ bool warp_master = (thread_rank % 32 == 0);
194
+ unsigned int warp_bit = 1 << warp_id;
195
+ unsigned int group_mask = get_group_mask(thread_rank, num_warps);
196
+
197
+ __syncwarp(0xFFFFFFFF);
198
+
199
+ if (warp_master) {
200
+ unsigned int old = atomicOr((unsigned int *)arrived, warp_bit);
201
+ if (((old | warp_bit) & group_mask) == group_mask) {
202
+ atomicAnd((unsigned int *)arrived, ~group_mask);
203
+ }
204
+ }
205
+ __syncwarp(0xFFFFFFFF);
206
+ }
207
+
208
+ // Wait for my warp to be released from the barrier. Warp must have arrived first.
209
+ _CG_STATIC_QUALIFIER void sync_warps_wait(volatile barrier_t *arrived, unsigned int thread_rank) {
210
+ unsigned int warp_id = thread_rank / 32;
211
+ unsigned int warp_bit = 1 << warp_id;
212
+
213
+ while(*arrived & warp_bit);
214
+ __syncwarp(0xFFFFFFFF);
215
+ }
216
+
217
+ // Arrive at my group barrier and block. Barrier is not released, even if every warp arrives.
218
+ // sync_warps_release needs to be called by some warp after this one.
219
+ _CG_STATIC_QUALIFIER void sync_warps_wait_for_release(
220
+ volatile barrier_t *arrived,
221
+ bool is_master,
222
+ unsigned int thread_rank,
223
+ unsigned int num_warps) {
224
+
225
+ unsigned int warp_id = thread_rank / 32;
226
+ unsigned int warp_bit = 1 << warp_id;
227
+
228
+ __syncwarp(0xFFFFFFFF);
229
+
230
+ if (is_master) {
231
+ atomicOr((unsigned int *)arrived, warp_bit);
232
+ while(*arrived & warp_bit);
233
+ }
234
+
235
+ __syncwarp(0xFFFFFFFF);
236
+ }
237
+
238
+ enum wait_for_warps_kind {
239
+ wait_for_all_other_warps,
240
+ wait_for_specific_warp
241
+ };
242
+
243
+ // Wait for a combinantion of warps specified by Kind parameter to arrive at the group barrier.
244
+ // This function does not arrive at the barrier.
245
+ template <wait_for_warps_kind Kind>
246
+ _CG_QUALIFIER void sync_warps_wait_for_warps(
247
+ unsigned int wait_warp_id, volatile barrier_t *arrived, unsigned int thread_rank, unsigned int num_warps);
248
+
249
+ template <>
250
+ _CG_QUALIFIER void sync_warps_wait_for_warps<wait_for_all_other_warps>(
251
+ unsigned int wait_warp_id,
252
+ volatile barrier_t *arrived,
253
+ unsigned int thread_rank,
254
+ unsigned int num_warps) {
255
+
256
+ unsigned int wait_mask = get_group_mask(thread_rank, num_warps);
257
+ wait_mask &= ~(1 << wait_warp_id);
258
+ while((*arrived & wait_mask) != wait_mask);
259
+ }
260
+
261
+ template <>
262
+ _CG_QUALIFIER void sync_warps_wait_for_warps<wait_for_specific_warp>(
263
+ unsigned int wait_warp_id,
264
+ volatile barrier_t *arrived,
265
+ unsigned int thread_rank,
266
+ unsigned int num_warps) {
267
+
268
+ unsigned int wait_mask = 1 << wait_warp_id;
269
+ while((*arrived & wait_mask) != wait_mask);
270
+ }
271
+
272
+ } // details
273
+
274
+ _CG_END_NAMESPACE
275
+
276
+ #endif // _CG_GRID_H
tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/include/cooperative_groups/scan.h ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 1993-2016 NVIDIA Corporation. All rights reserved.
2
+ *
3
+ * NOTICE TO LICENSEE:
4
+ *
5
+ * The source code and/or documentation ("Licensed Deliverables") are
6
+ * subject to NVIDIA intellectual property rights under U.S. and
7
+ * international Copyright laws.
8
+ *
9
+ * The Licensed Deliverables contained herein are PROPRIETARY and
10
+ * CONFIDENTIAL to NVIDIA and are being provided under the terms and
11
+ * conditions of a form of NVIDIA software license agreement by and
12
+ * between NVIDIA and Licensee ("License Agreement") or electronically
13
+ * accepted by Licensee. Notwithstanding any terms or conditions to
14
+ * the contrary in the License Agreement, reproduction or disclosure
15
+ * of the Licensed Deliverables to any third party without the express
16
+ * written consent of NVIDIA is prohibited.
17
+ *
18
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
19
+ * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE
20
+ * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. THEY ARE
21
+ * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND.
22
+ * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED
23
+ * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
24
+ * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE.
25
+ * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE
26
+ * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY
27
+ * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY
28
+ * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
29
+ * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
30
+ * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
31
+ * OF THESE LICENSED DELIVERABLES.
32
+ *
33
+ * U.S. Government End Users. These Licensed Deliverables are a
34
+ * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT
35
+ * 1995), consisting of "commercial computer software" and "commercial
36
+ * computer software documentation" as such terms are used in 48
37
+ * C.F.R. 12.212 (SEPT 1995) and are provided to the U.S. Government
38
+ * only as a commercial end item. Consistent with 48 C.F.R.12.212 and
39
+ * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all
40
+ * U.S. Government End Users acquire the Licensed Deliverables with
41
+ * only those rights set forth herein.
42
+ *
43
+ * Any use of the Licensed Deliverables in individual and commercial
44
+ * software must include, in the user documentation and internal
45
+ * comments to the code, the above Disclaimer and U.S. Government End
46
+ * Users Notice.
47
+ */
48
+
49
+ #ifndef _COOPERATIVE_GROUPS_SCAN_H
50
+ #define _COOPERATIVE_GROUPS_SCAN_H
51
+
52
+ #include "../cooperative_groups.h"
53
+ #include "details/info.h"
54
+
55
+ #ifdef _CG_CPP11_FEATURES
56
+ # include "details/scan.h"
57
+ #else
58
+ # error This file requires compiler support for the ISO C++ 2011 standard. This support must be enabled with the \
59
+ -std=c++11 compiler option.
60
+ #endif
61
+
62
+
63
+ #endif //_COOPERATIVE_GROUPS_SCAN_H
tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/lib/__init__.py ADDED
File without changes
tuning-competition-baseline/.venv/lib/python3.11/site-packages/nvidia/cuda_runtime/lib/libOpenCL.so.1 ADDED
Binary file (30.9 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/idna/compat.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .core import *
2
+ from .codec import *
3
+ from typing import Any, Union
4
+
5
+ def ToASCII(label: str) -> bytes:
6
+ return encode(label)
7
+
8
+ def ToUnicode(label: Union[bytes, bytearray]) -> str:
9
+ return decode(label)
10
+
11
+ def nameprep(s: Any) -> None:
12
+ raise NotImplementedError('IDNA 2008 does not utilise nameprep protocol')
13
+
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/adapters.py ADDED
@@ -0,0 +1,719 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.adapters
3
+ ~~~~~~~~~~~~~~~~~
4
+
5
+ This module contains the transport adapters that Requests uses to define
6
+ and maintain connections.
7
+ """
8
+
9
+ import os.path
10
+ import socket # noqa: F401
11
+ import typing
12
+ import warnings
13
+
14
+ from pip._vendor.urllib3.exceptions import ClosedPoolError, ConnectTimeoutError
15
+ from pip._vendor.urllib3.exceptions import HTTPError as _HTTPError
16
+ from pip._vendor.urllib3.exceptions import InvalidHeader as _InvalidHeader
17
+ from pip._vendor.urllib3.exceptions import (
18
+ LocationValueError,
19
+ MaxRetryError,
20
+ NewConnectionError,
21
+ ProtocolError,
22
+ )
23
+ from pip._vendor.urllib3.exceptions import ProxyError as _ProxyError
24
+ from pip._vendor.urllib3.exceptions import ReadTimeoutError, ResponseError
25
+ from pip._vendor.urllib3.exceptions import SSLError as _SSLError
26
+ from pip._vendor.urllib3.poolmanager import PoolManager, proxy_from_url
27
+ from pip._vendor.urllib3.util import Timeout as TimeoutSauce
28
+ from pip._vendor.urllib3.util import parse_url
29
+ from pip._vendor.urllib3.util.retry import Retry
30
+ from pip._vendor.urllib3.util.ssl_ import create_urllib3_context
31
+
32
+ from .auth import _basic_auth_str
33
+ from .compat import basestring, urlparse
34
+ from .cookies import extract_cookies_to_jar
35
+ from .exceptions import (
36
+ ConnectionError,
37
+ ConnectTimeout,
38
+ InvalidHeader,
39
+ InvalidProxyURL,
40
+ InvalidSchema,
41
+ InvalidURL,
42
+ ProxyError,
43
+ ReadTimeout,
44
+ RetryError,
45
+ SSLError,
46
+ )
47
+ from .models import Response
48
+ from .structures import CaseInsensitiveDict
49
+ from .utils import (
50
+ DEFAULT_CA_BUNDLE_PATH,
51
+ extract_zipped_paths,
52
+ get_auth_from_url,
53
+ get_encoding_from_headers,
54
+ prepend_scheme_if_needed,
55
+ select_proxy,
56
+ urldefragauth,
57
+ )
58
+
59
+ try:
60
+ from pip._vendor.urllib3.contrib.socks import SOCKSProxyManager
61
+ except ImportError:
62
+
63
+ def SOCKSProxyManager(*args, **kwargs):
64
+ raise InvalidSchema("Missing dependencies for SOCKS support.")
65
+
66
+
67
+ if typing.TYPE_CHECKING:
68
+ from .models import PreparedRequest
69
+
70
+
71
+ DEFAULT_POOLBLOCK = False
72
+ DEFAULT_POOLSIZE = 10
73
+ DEFAULT_RETRIES = 0
74
+ DEFAULT_POOL_TIMEOUT = None
75
+
76
+
77
+ try:
78
+ import ssl # noqa: F401
79
+
80
+ _preloaded_ssl_context = create_urllib3_context()
81
+ _preloaded_ssl_context.load_verify_locations(
82
+ extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)
83
+ )
84
+ except ImportError:
85
+ # Bypass default SSLContext creation when Python
86
+ # interpreter isn't built with the ssl module.
87
+ _preloaded_ssl_context = None
88
+
89
+
90
+ def _urllib3_request_context(
91
+ request: "PreparedRequest",
92
+ verify: "bool | str | None",
93
+ client_cert: "typing.Tuple[str, str] | str | None",
94
+ poolmanager: "PoolManager",
95
+ ) -> "(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])":
96
+ host_params = {}
97
+ pool_kwargs = {}
98
+ parsed_request_url = urlparse(request.url)
99
+ scheme = parsed_request_url.scheme.lower()
100
+ port = parsed_request_url.port
101
+
102
+ # Determine if we have and should use our default SSLContext
103
+ # to optimize performance on standard requests.
104
+ poolmanager_kwargs = getattr(poolmanager, "connection_pool_kw", {})
105
+ has_poolmanager_ssl_context = poolmanager_kwargs.get("ssl_context")
106
+ should_use_default_ssl_context = (
107
+ _preloaded_ssl_context is not None and not has_poolmanager_ssl_context
108
+ )
109
+
110
+ cert_reqs = "CERT_REQUIRED"
111
+ if verify is False:
112
+ cert_reqs = "CERT_NONE"
113
+ elif verify is True and should_use_default_ssl_context:
114
+ pool_kwargs["ssl_context"] = _preloaded_ssl_context
115
+ elif isinstance(verify, str):
116
+ if not os.path.isdir(verify):
117
+ pool_kwargs["ca_certs"] = verify
118
+ else:
119
+ pool_kwargs["ca_cert_dir"] = verify
120
+ pool_kwargs["cert_reqs"] = cert_reqs
121
+ if client_cert is not None:
122
+ if isinstance(client_cert, tuple) and len(client_cert) == 2:
123
+ pool_kwargs["cert_file"] = client_cert[0]
124
+ pool_kwargs["key_file"] = client_cert[1]
125
+ else:
126
+ # According to our docs, we allow users to specify just the client
127
+ # cert path
128
+ pool_kwargs["cert_file"] = client_cert
129
+ host_params = {
130
+ "scheme": scheme,
131
+ "host": parsed_request_url.hostname,
132
+ "port": port,
133
+ }
134
+ return host_params, pool_kwargs
135
+
136
+
137
+ class BaseAdapter:
138
+ """The Base Transport Adapter"""
139
+
140
+ def __init__(self):
141
+ super().__init__()
142
+
143
+ def send(
144
+ self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
145
+ ):
146
+ """Sends PreparedRequest object. Returns Response object.
147
+
148
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
149
+ :param stream: (optional) Whether to stream the request content.
150
+ :param timeout: (optional) How long to wait for the server to send
151
+ data before giving up, as a float, or a :ref:`(connect timeout,
152
+ read timeout) <timeouts>` tuple.
153
+ :type timeout: float or tuple
154
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
155
+ the server's TLS certificate, or a string, in which case it must be a path
156
+ to a CA bundle to use
157
+ :param cert: (optional) Any user-provided SSL certificate to be trusted.
158
+ :param proxies: (optional) The proxies dictionary to apply to the request.
159
+ """
160
+ raise NotImplementedError
161
+
162
+ def close(self):
163
+ """Cleans up adapter specific items."""
164
+ raise NotImplementedError
165
+
166
+
167
+ class HTTPAdapter(BaseAdapter):
168
+ """The built-in HTTP Adapter for urllib3.
169
+
170
+ Provides a general-case interface for Requests sessions to contact HTTP and
171
+ HTTPS urls by implementing the Transport Adapter interface. This class will
172
+ usually be created by the :class:`Session <Session>` class under the
173
+ covers.
174
+
175
+ :param pool_connections: The number of urllib3 connection pools to cache.
176
+ :param pool_maxsize: The maximum number of connections to save in the pool.
177
+ :param max_retries: The maximum number of retries each connection
178
+ should attempt. Note, this applies only to failed DNS lookups, socket
179
+ connections and connection timeouts, never to requests where data has
180
+ made it to the server. By default, Requests does not retry failed
181
+ connections. If you need granular control over the conditions under
182
+ which we retry a request, import urllib3's ``Retry`` class and pass
183
+ that instead.
184
+ :param pool_block: Whether the connection pool should block for connections.
185
+
186
+ Usage::
187
+
188
+ >>> import requests
189
+ >>> s = requests.Session()
190
+ >>> a = requests.adapters.HTTPAdapter(max_retries=3)
191
+ >>> s.mount('http://', a)
192
+ """
193
+
194
+ __attrs__ = [
195
+ "max_retries",
196
+ "config",
197
+ "_pool_connections",
198
+ "_pool_maxsize",
199
+ "_pool_block",
200
+ ]
201
+
202
+ def __init__(
203
+ self,
204
+ pool_connections=DEFAULT_POOLSIZE,
205
+ pool_maxsize=DEFAULT_POOLSIZE,
206
+ max_retries=DEFAULT_RETRIES,
207
+ pool_block=DEFAULT_POOLBLOCK,
208
+ ):
209
+ if max_retries == DEFAULT_RETRIES:
210
+ self.max_retries = Retry(0, read=False)
211
+ else:
212
+ self.max_retries = Retry.from_int(max_retries)
213
+ self.config = {}
214
+ self.proxy_manager = {}
215
+
216
+ super().__init__()
217
+
218
+ self._pool_connections = pool_connections
219
+ self._pool_maxsize = pool_maxsize
220
+ self._pool_block = pool_block
221
+
222
+ self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
223
+
224
+ def __getstate__(self):
225
+ return {attr: getattr(self, attr, None) for attr in self.__attrs__}
226
+
227
+ def __setstate__(self, state):
228
+ # Can't handle by adding 'proxy_manager' to self.__attrs__ because
229
+ # self.poolmanager uses a lambda function, which isn't pickleable.
230
+ self.proxy_manager = {}
231
+ self.config = {}
232
+
233
+ for attr, value in state.items():
234
+ setattr(self, attr, value)
235
+
236
+ self.init_poolmanager(
237
+ self._pool_connections, self._pool_maxsize, block=self._pool_block
238
+ )
239
+
240
+ def init_poolmanager(
241
+ self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs
242
+ ):
243
+ """Initializes a urllib3 PoolManager.
244
+
245
+ This method should not be called from user code, and is only
246
+ exposed for use when subclassing the
247
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
248
+
249
+ :param connections: The number of urllib3 connection pools to cache.
250
+ :param maxsize: The maximum number of connections to save in the pool.
251
+ :param block: Block when no free connections are available.
252
+ :param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
253
+ """
254
+ # save these values for pickling
255
+ self._pool_connections = connections
256
+ self._pool_maxsize = maxsize
257
+ self._pool_block = block
258
+
259
+ self.poolmanager = PoolManager(
260
+ num_pools=connections,
261
+ maxsize=maxsize,
262
+ block=block,
263
+ **pool_kwargs,
264
+ )
265
+
266
+ def proxy_manager_for(self, proxy, **proxy_kwargs):
267
+ """Return urllib3 ProxyManager for the given proxy.
268
+
269
+ This method should not be called from user code, and is only
270
+ exposed for use when subclassing the
271
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
272
+
273
+ :param proxy: The proxy to return a urllib3 ProxyManager for.
274
+ :param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
275
+ :returns: ProxyManager
276
+ :rtype: urllib3.ProxyManager
277
+ """
278
+ if proxy in self.proxy_manager:
279
+ manager = self.proxy_manager[proxy]
280
+ elif proxy.lower().startswith("socks"):
281
+ username, password = get_auth_from_url(proxy)
282
+ manager = self.proxy_manager[proxy] = SOCKSProxyManager(
283
+ proxy,
284
+ username=username,
285
+ password=password,
286
+ num_pools=self._pool_connections,
287
+ maxsize=self._pool_maxsize,
288
+ block=self._pool_block,
289
+ **proxy_kwargs,
290
+ )
291
+ else:
292
+ proxy_headers = self.proxy_headers(proxy)
293
+ manager = self.proxy_manager[proxy] = proxy_from_url(
294
+ proxy,
295
+ proxy_headers=proxy_headers,
296
+ num_pools=self._pool_connections,
297
+ maxsize=self._pool_maxsize,
298
+ block=self._pool_block,
299
+ **proxy_kwargs,
300
+ )
301
+
302
+ return manager
303
+
304
+ def cert_verify(self, conn, url, verify, cert):
305
+ """Verify a SSL certificate. This method should not be called from user
306
+ code, and is only exposed for use when subclassing the
307
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
308
+
309
+ :param conn: The urllib3 connection object associated with the cert.
310
+ :param url: The requested URL.
311
+ :param verify: Either a boolean, in which case it controls whether we verify
312
+ the server's TLS certificate, or a string, in which case it must be a path
313
+ to a CA bundle to use
314
+ :param cert: The SSL certificate to verify.
315
+ """
316
+ if url.lower().startswith("https") and verify:
317
+ conn.cert_reqs = "CERT_REQUIRED"
318
+
319
+ # Only load the CA certificates if 'verify' is a string indicating the CA bundle to use.
320
+ # Otherwise, if verify is a boolean, we don't load anything since
321
+ # the connection will be using a context with the default certificates already loaded,
322
+ # and this avoids a call to the slow load_verify_locations()
323
+ if verify is not True:
324
+ # `verify` must be a str with a path then
325
+ cert_loc = verify
326
+
327
+ if not os.path.exists(cert_loc):
328
+ raise OSError(
329
+ f"Could not find a suitable TLS CA certificate bundle, "
330
+ f"invalid path: {cert_loc}"
331
+ )
332
+
333
+ if not os.path.isdir(cert_loc):
334
+ conn.ca_certs = cert_loc
335
+ else:
336
+ conn.ca_cert_dir = cert_loc
337
+ else:
338
+ conn.cert_reqs = "CERT_NONE"
339
+ conn.ca_certs = None
340
+ conn.ca_cert_dir = None
341
+
342
+ if cert:
343
+ if not isinstance(cert, basestring):
344
+ conn.cert_file = cert[0]
345
+ conn.key_file = cert[1]
346
+ else:
347
+ conn.cert_file = cert
348
+ conn.key_file = None
349
+ if conn.cert_file and not os.path.exists(conn.cert_file):
350
+ raise OSError(
351
+ f"Could not find the TLS certificate file, "
352
+ f"invalid path: {conn.cert_file}"
353
+ )
354
+ if conn.key_file and not os.path.exists(conn.key_file):
355
+ raise OSError(
356
+ f"Could not find the TLS key file, invalid path: {conn.key_file}"
357
+ )
358
+
359
+ def build_response(self, req, resp):
360
+ """Builds a :class:`Response <requests.Response>` object from a urllib3
361
+ response. This should not be called from user code, and is only exposed
362
+ for use when subclassing the
363
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
364
+
365
+ :param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
366
+ :param resp: The urllib3 response object.
367
+ :rtype: requests.Response
368
+ """
369
+ response = Response()
370
+
371
+ # Fallback to None if there's no status_code, for whatever reason.
372
+ response.status_code = getattr(resp, "status", None)
373
+
374
+ # Make headers case-insensitive.
375
+ response.headers = CaseInsensitiveDict(getattr(resp, "headers", {}))
376
+
377
+ # Set encoding.
378
+ response.encoding = get_encoding_from_headers(response.headers)
379
+ response.raw = resp
380
+ response.reason = response.raw.reason
381
+
382
+ if isinstance(req.url, bytes):
383
+ response.url = req.url.decode("utf-8")
384
+ else:
385
+ response.url = req.url
386
+
387
+ # Add new cookies from the server.
388
+ extract_cookies_to_jar(response.cookies, req, resp)
389
+
390
+ # Give the Response some context.
391
+ response.request = req
392
+ response.connection = self
393
+
394
+ return response
395
+
396
+ def build_connection_pool_key_attributes(self, request, verify, cert=None):
397
+ """Build the PoolKey attributes used by urllib3 to return a connection.
398
+
399
+ This looks at the PreparedRequest, the user-specified verify value,
400
+ and the value of the cert parameter to determine what PoolKey values
401
+ to use to select a connection from a given urllib3 Connection Pool.
402
+
403
+ The SSL related pool key arguments are not consistently set. As of
404
+ this writing, use the following to determine what keys may be in that
405
+ dictionary:
406
+
407
+ * If ``verify`` is ``True``, ``"ssl_context"`` will be set and will be the
408
+ default Requests SSL Context
409
+ * If ``verify`` is ``False``, ``"ssl_context"`` will not be set but
410
+ ``"cert_reqs"`` will be set
411
+ * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)
412
+ ``"ca_certs"`` will be set if the string is not a directory recognized
413
+ by :py:func:`os.path.isdir`, otherwise ``"ca_certs_dir"`` will be
414
+ set.
415
+ * If ``"cert"`` is specified, ``"cert_file"`` will always be set. If
416
+ ``"cert"`` is a tuple with a second item, ``"key_file"`` will also
417
+ be present
418
+
419
+ To override these settings, one may subclass this class, call this
420
+ method and use the above logic to change parameters as desired. For
421
+ example, if one wishes to use a custom :py:class:`ssl.SSLContext` one
422
+ must both set ``"ssl_context"`` and based on what else they require,
423
+ alter the other keys to ensure the desired behaviour.
424
+
425
+ :param request:
426
+ The PreparedReqest being sent over the connection.
427
+ :type request:
428
+ :class:`~requests.models.PreparedRequest`
429
+ :param verify:
430
+ Either a boolean, in which case it controls whether
431
+ we verify the server's TLS certificate, or a string, in which case it
432
+ must be a path to a CA bundle to use.
433
+ :param cert:
434
+ (optional) Any user-provided SSL certificate for client
435
+ authentication (a.k.a., mTLS). This may be a string (i.e., just
436
+ the path to a file which holds both certificate and key) or a
437
+ tuple of length 2 with the certificate file path and key file
438
+ path.
439
+ :returns:
440
+ A tuple of two dictionaries. The first is the "host parameters"
441
+ portion of the Pool Key including scheme, hostname, and port. The
442
+ second is a dictionary of SSLContext related parameters.
443
+ """
444
+ return _urllib3_request_context(request, verify, cert, self.poolmanager)
445
+
446
+ def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):
447
+ """Returns a urllib3 connection for the given request and TLS settings.
448
+ This should not be called from user code, and is only exposed for use
449
+ when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
450
+
451
+ :param request:
452
+ The :class:`PreparedRequest <PreparedRequest>` object to be sent
453
+ over the connection.
454
+ :param verify:
455
+ Either a boolean, in which case it controls whether we verify the
456
+ server's TLS certificate, or a string, in which case it must be a
457
+ path to a CA bundle to use.
458
+ :param proxies:
459
+ (optional) The proxies dictionary to apply to the request.
460
+ :param cert:
461
+ (optional) Any user-provided SSL certificate to be used for client
462
+ authentication (a.k.a., mTLS).
463
+ :rtype:
464
+ urllib3.ConnectionPool
465
+ """
466
+ proxy = select_proxy(request.url, proxies)
467
+ try:
468
+ host_params, pool_kwargs = self.build_connection_pool_key_attributes(
469
+ request,
470
+ verify,
471
+ cert,
472
+ )
473
+ except ValueError as e:
474
+ raise InvalidURL(e, request=request)
475
+ if proxy:
476
+ proxy = prepend_scheme_if_needed(proxy, "http")
477
+ proxy_url = parse_url(proxy)
478
+ if not proxy_url.host:
479
+ raise InvalidProxyURL(
480
+ "Please check proxy URL. It is malformed "
481
+ "and could be missing the host."
482
+ )
483
+ proxy_manager = self.proxy_manager_for(proxy)
484
+ conn = proxy_manager.connection_from_host(
485
+ **host_params, pool_kwargs=pool_kwargs
486
+ )
487
+ else:
488
+ # Only scheme should be lower case
489
+ conn = self.poolmanager.connection_from_host(
490
+ **host_params, pool_kwargs=pool_kwargs
491
+ )
492
+
493
+ return conn
494
+
495
+ def get_connection(self, url, proxies=None):
496
+ """DEPRECATED: Users should move to `get_connection_with_tls_context`
497
+ for all subclasses of HTTPAdapter using Requests>=2.32.2.
498
+
499
+ Returns a urllib3 connection for the given URL. This should not be
500
+ called from user code, and is only exposed for use when subclassing the
501
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
502
+
503
+ :param url: The URL to connect to.
504
+ :param proxies: (optional) A Requests-style dictionary of proxies used on this request.
505
+ :rtype: urllib3.ConnectionPool
506
+ """
507
+ warnings.warn(
508
+ (
509
+ "`get_connection` has been deprecated in favor of "
510
+ "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses "
511
+ "will need to migrate for Requests>=2.32.2. Please see "
512
+ "https://github.com/psf/requests/pull/6710 for more details."
513
+ ),
514
+ DeprecationWarning,
515
+ )
516
+ proxy = select_proxy(url, proxies)
517
+
518
+ if proxy:
519
+ proxy = prepend_scheme_if_needed(proxy, "http")
520
+ proxy_url = parse_url(proxy)
521
+ if not proxy_url.host:
522
+ raise InvalidProxyURL(
523
+ "Please check proxy URL. It is malformed "
524
+ "and could be missing the host."
525
+ )
526
+ proxy_manager = self.proxy_manager_for(proxy)
527
+ conn = proxy_manager.connection_from_url(url)
528
+ else:
529
+ # Only scheme should be lower case
530
+ parsed = urlparse(url)
531
+ url = parsed.geturl()
532
+ conn = self.poolmanager.connection_from_url(url)
533
+
534
+ return conn
535
+
536
+ def close(self):
537
+ """Disposes of any internal state.
538
+
539
+ Currently, this closes the PoolManager and any active ProxyManager,
540
+ which closes any pooled connections.
541
+ """
542
+ self.poolmanager.clear()
543
+ for proxy in self.proxy_manager.values():
544
+ proxy.clear()
545
+
546
+ def request_url(self, request, proxies):
547
+ """Obtain the url to use when making the final request.
548
+
549
+ If the message is being sent through a HTTP proxy, the full URL has to
550
+ be used. Otherwise, we should only use the path portion of the URL.
551
+
552
+ This should not be called from user code, and is only exposed for use
553
+ when subclassing the
554
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
555
+
556
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
557
+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
558
+ :rtype: str
559
+ """
560
+ proxy = select_proxy(request.url, proxies)
561
+ scheme = urlparse(request.url).scheme
562
+
563
+ is_proxied_http_request = proxy and scheme != "https"
564
+ using_socks_proxy = False
565
+ if proxy:
566
+ proxy_scheme = urlparse(proxy).scheme.lower()
567
+ using_socks_proxy = proxy_scheme.startswith("socks")
568
+
569
+ url = request.path_url
570
+ if url.startswith("//"): # Don't confuse urllib3
571
+ url = f"/{url.lstrip('/')}"
572
+
573
+ if is_proxied_http_request and not using_socks_proxy:
574
+ url = urldefragauth(request.url)
575
+
576
+ return url
577
+
578
+ def add_headers(self, request, **kwargs):
579
+ """Add any headers needed by the connection. As of v2.0 this does
580
+ nothing by default, but is left for overriding by users that subclass
581
+ the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
582
+
583
+ This should not be called from user code, and is only exposed for use
584
+ when subclassing the
585
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
586
+
587
+ :param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
588
+ :param kwargs: The keyword arguments from the call to send().
589
+ """
590
+ pass
591
+
592
+ def proxy_headers(self, proxy):
593
+ """Returns a dictionary of the headers to add to any request sent
594
+ through a proxy. This works with urllib3 magic to ensure that they are
595
+ correctly sent to the proxy, rather than in a tunnelled request if
596
+ CONNECT is being used.
597
+
598
+ This should not be called from user code, and is only exposed for use
599
+ when subclassing the
600
+ :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
601
+
602
+ :param proxy: The url of the proxy being used for this request.
603
+ :rtype: dict
604
+ """
605
+ headers = {}
606
+ username, password = get_auth_from_url(proxy)
607
+
608
+ if username:
609
+ headers["Proxy-Authorization"] = _basic_auth_str(username, password)
610
+
611
+ return headers
612
+
613
+ def send(
614
+ self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None
615
+ ):
616
+ """Sends PreparedRequest object. Returns Response object.
617
+
618
+ :param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
619
+ :param stream: (optional) Whether to stream the request content.
620
+ :param timeout: (optional) How long to wait for the server to send
621
+ data before giving up, as a float, or a :ref:`(connect timeout,
622
+ read timeout) <timeouts>` tuple.
623
+ :type timeout: float or tuple or urllib3 Timeout object
624
+ :param verify: (optional) Either a boolean, in which case it controls whether
625
+ we verify the server's TLS certificate, or a string, in which case it
626
+ must be a path to a CA bundle to use
627
+ :param cert: (optional) Any user-provided SSL certificate to be trusted.
628
+ :param proxies: (optional) The proxies dictionary to apply to the request.
629
+ :rtype: requests.Response
630
+ """
631
+
632
+ try:
633
+ conn = self.get_connection_with_tls_context(
634
+ request, verify, proxies=proxies, cert=cert
635
+ )
636
+ except LocationValueError as e:
637
+ raise InvalidURL(e, request=request)
638
+
639
+ self.cert_verify(conn, request.url, verify, cert)
640
+ url = self.request_url(request, proxies)
641
+ self.add_headers(
642
+ request,
643
+ stream=stream,
644
+ timeout=timeout,
645
+ verify=verify,
646
+ cert=cert,
647
+ proxies=proxies,
648
+ )
649
+
650
+ chunked = not (request.body is None or "Content-Length" in request.headers)
651
+
652
+ if isinstance(timeout, tuple):
653
+ try:
654
+ connect, read = timeout
655
+ timeout = TimeoutSauce(connect=connect, read=read)
656
+ except ValueError:
657
+ raise ValueError(
658
+ f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, "
659
+ f"or a single float to set both timeouts to the same value."
660
+ )
661
+ elif isinstance(timeout, TimeoutSauce):
662
+ pass
663
+ else:
664
+ timeout = TimeoutSauce(connect=timeout, read=timeout)
665
+
666
+ try:
667
+ resp = conn.urlopen(
668
+ method=request.method,
669
+ url=url,
670
+ body=request.body,
671
+ headers=request.headers,
672
+ redirect=False,
673
+ assert_same_host=False,
674
+ preload_content=False,
675
+ decode_content=False,
676
+ retries=self.max_retries,
677
+ timeout=timeout,
678
+ chunked=chunked,
679
+ )
680
+
681
+ except (ProtocolError, OSError) as err:
682
+ raise ConnectionError(err, request=request)
683
+
684
+ except MaxRetryError as e:
685
+ if isinstance(e.reason, ConnectTimeoutError):
686
+ # TODO: Remove this in 3.0.0: see #2811
687
+ if not isinstance(e.reason, NewConnectionError):
688
+ raise ConnectTimeout(e, request=request)
689
+
690
+ if isinstance(e.reason, ResponseError):
691
+ raise RetryError(e, request=request)
692
+
693
+ if isinstance(e.reason, _ProxyError):
694
+ raise ProxyError(e, request=request)
695
+
696
+ if isinstance(e.reason, _SSLError):
697
+ # This branch is for urllib3 v1.22 and later.
698
+ raise SSLError(e, request=request)
699
+
700
+ raise ConnectionError(e, request=request)
701
+
702
+ except ClosedPoolError as e:
703
+ raise ConnectionError(e, request=request)
704
+
705
+ except _ProxyError as e:
706
+ raise ProxyError(e)
707
+
708
+ except (_SSLError, _HTTPError) as e:
709
+ if isinstance(e, _SSLError):
710
+ # This branch is for urllib3 versions earlier than v1.22
711
+ raise SSLError(e, request=request)
712
+ elif isinstance(e, ReadTimeoutError):
713
+ raise ReadTimeout(e, request=request)
714
+ elif isinstance(e, _InvalidHeader):
715
+ raise InvalidHeader(e, request=request)
716
+ else:
717
+ raise
718
+
719
+ return self.build_response(request, resp)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/auth.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.auth
3
+ ~~~~~~~~~~~~~
4
+
5
+ This module contains the authentication handlers for Requests.
6
+ """
7
+
8
+ import hashlib
9
+ import os
10
+ import re
11
+ import threading
12
+ import time
13
+ import warnings
14
+ from base64 import b64encode
15
+
16
+ from ._internal_utils import to_native_string
17
+ from .compat import basestring, str, urlparse
18
+ from .cookies import extract_cookies_to_jar
19
+ from .utils import parse_dict_header
20
+
21
+ CONTENT_TYPE_FORM_URLENCODED = "application/x-www-form-urlencoded"
22
+ CONTENT_TYPE_MULTI_PART = "multipart/form-data"
23
+
24
+
25
+ def _basic_auth_str(username, password):
26
+ """Returns a Basic Auth string."""
27
+
28
+ # "I want us to put a big-ol' comment on top of it that
29
+ # says that this behaviour is dumb but we need to preserve
30
+ # it because people are relying on it."
31
+ # - Lukasa
32
+ #
33
+ # These are here solely to maintain backwards compatibility
34
+ # for things like ints. This will be removed in 3.0.0.
35
+ if not isinstance(username, basestring):
36
+ warnings.warn(
37
+ "Non-string usernames will no longer be supported in Requests "
38
+ "3.0.0. Please convert the object you've passed in ({!r}) to "
39
+ "a string or bytes object in the near future to avoid "
40
+ "problems.".format(username),
41
+ category=DeprecationWarning,
42
+ )
43
+ username = str(username)
44
+
45
+ if not isinstance(password, basestring):
46
+ warnings.warn(
47
+ "Non-string passwords will no longer be supported in Requests "
48
+ "3.0.0. Please convert the object you've passed in ({!r}) to "
49
+ "a string or bytes object in the near future to avoid "
50
+ "problems.".format(type(password)),
51
+ category=DeprecationWarning,
52
+ )
53
+ password = str(password)
54
+ # -- End Removal --
55
+
56
+ if isinstance(username, str):
57
+ username = username.encode("latin1")
58
+
59
+ if isinstance(password, str):
60
+ password = password.encode("latin1")
61
+
62
+ authstr = "Basic " + to_native_string(
63
+ b64encode(b":".join((username, password))).strip()
64
+ )
65
+
66
+ return authstr
67
+
68
+
69
+ class AuthBase:
70
+ """Base class that all auth implementations derive from"""
71
+
72
+ def __call__(self, r):
73
+ raise NotImplementedError("Auth hooks must be callable.")
74
+
75
+
76
+ class HTTPBasicAuth(AuthBase):
77
+ """Attaches HTTP Basic Authentication to the given Request object."""
78
+
79
+ def __init__(self, username, password):
80
+ self.username = username
81
+ self.password = password
82
+
83
+ def __eq__(self, other):
84
+ return all(
85
+ [
86
+ self.username == getattr(other, "username", None),
87
+ self.password == getattr(other, "password", None),
88
+ ]
89
+ )
90
+
91
+ def __ne__(self, other):
92
+ return not self == other
93
+
94
+ def __call__(self, r):
95
+ r.headers["Authorization"] = _basic_auth_str(self.username, self.password)
96
+ return r
97
+
98
+
99
+ class HTTPProxyAuth(HTTPBasicAuth):
100
+ """Attaches HTTP Proxy Authentication to a given Request object."""
101
+
102
+ def __call__(self, r):
103
+ r.headers["Proxy-Authorization"] = _basic_auth_str(self.username, self.password)
104
+ return r
105
+
106
+
107
+ class HTTPDigestAuth(AuthBase):
108
+ """Attaches HTTP Digest Authentication to the given Request object."""
109
+
110
+ def __init__(self, username, password):
111
+ self.username = username
112
+ self.password = password
113
+ # Keep state in per-thread local storage
114
+ self._thread_local = threading.local()
115
+
116
+ def init_per_thread_state(self):
117
+ # Ensure state is initialized just once per-thread
118
+ if not hasattr(self._thread_local, "init"):
119
+ self._thread_local.init = True
120
+ self._thread_local.last_nonce = ""
121
+ self._thread_local.nonce_count = 0
122
+ self._thread_local.chal = {}
123
+ self._thread_local.pos = None
124
+ self._thread_local.num_401_calls = None
125
+
126
+ def build_digest_header(self, method, url):
127
+ """
128
+ :rtype: str
129
+ """
130
+
131
+ realm = self._thread_local.chal["realm"]
132
+ nonce = self._thread_local.chal["nonce"]
133
+ qop = self._thread_local.chal.get("qop")
134
+ algorithm = self._thread_local.chal.get("algorithm")
135
+ opaque = self._thread_local.chal.get("opaque")
136
+ hash_utf8 = None
137
+
138
+ if algorithm is None:
139
+ _algorithm = "MD5"
140
+ else:
141
+ _algorithm = algorithm.upper()
142
+ # lambdas assume digest modules are imported at the top level
143
+ if _algorithm == "MD5" or _algorithm == "MD5-SESS":
144
+
145
+ def md5_utf8(x):
146
+ if isinstance(x, str):
147
+ x = x.encode("utf-8")
148
+ return hashlib.md5(x).hexdigest()
149
+
150
+ hash_utf8 = md5_utf8
151
+ elif _algorithm == "SHA":
152
+
153
+ def sha_utf8(x):
154
+ if isinstance(x, str):
155
+ x = x.encode("utf-8")
156
+ return hashlib.sha1(x).hexdigest()
157
+
158
+ hash_utf8 = sha_utf8
159
+ elif _algorithm == "SHA-256":
160
+
161
+ def sha256_utf8(x):
162
+ if isinstance(x, str):
163
+ x = x.encode("utf-8")
164
+ return hashlib.sha256(x).hexdigest()
165
+
166
+ hash_utf8 = sha256_utf8
167
+ elif _algorithm == "SHA-512":
168
+
169
+ def sha512_utf8(x):
170
+ if isinstance(x, str):
171
+ x = x.encode("utf-8")
172
+ return hashlib.sha512(x).hexdigest()
173
+
174
+ hash_utf8 = sha512_utf8
175
+
176
+ KD = lambda s, d: hash_utf8(f"{s}:{d}") # noqa:E731
177
+
178
+ if hash_utf8 is None:
179
+ return None
180
+
181
+ # XXX not implemented yet
182
+ entdig = None
183
+ p_parsed = urlparse(url)
184
+ #: path is request-uri defined in RFC 2616 which should not be empty
185
+ path = p_parsed.path or "/"
186
+ if p_parsed.query:
187
+ path += f"?{p_parsed.query}"
188
+
189
+ A1 = f"{self.username}:{realm}:{self.password}"
190
+ A2 = f"{method}:{path}"
191
+
192
+ HA1 = hash_utf8(A1)
193
+ HA2 = hash_utf8(A2)
194
+
195
+ if nonce == self._thread_local.last_nonce:
196
+ self._thread_local.nonce_count += 1
197
+ else:
198
+ self._thread_local.nonce_count = 1
199
+ ncvalue = f"{self._thread_local.nonce_count:08x}"
200
+ s = str(self._thread_local.nonce_count).encode("utf-8")
201
+ s += nonce.encode("utf-8")
202
+ s += time.ctime().encode("utf-8")
203
+ s += os.urandom(8)
204
+
205
+ cnonce = hashlib.sha1(s).hexdigest()[:16]
206
+ if _algorithm == "MD5-SESS":
207
+ HA1 = hash_utf8(f"{HA1}:{nonce}:{cnonce}")
208
+
209
+ if not qop:
210
+ respdig = KD(HA1, f"{nonce}:{HA2}")
211
+ elif qop == "auth" or "auth" in qop.split(","):
212
+ noncebit = f"{nonce}:{ncvalue}:{cnonce}:auth:{HA2}"
213
+ respdig = KD(HA1, noncebit)
214
+ else:
215
+ # XXX handle auth-int.
216
+ return None
217
+
218
+ self._thread_local.last_nonce = nonce
219
+
220
+ # XXX should the partial digests be encoded too?
221
+ base = (
222
+ f'username="{self.username}", realm="{realm}", nonce="{nonce}", '
223
+ f'uri="{path}", response="{respdig}"'
224
+ )
225
+ if opaque:
226
+ base += f', opaque="{opaque}"'
227
+ if algorithm:
228
+ base += f', algorithm="{algorithm}"'
229
+ if entdig:
230
+ base += f', digest="{entdig}"'
231
+ if qop:
232
+ base += f', qop="auth", nc={ncvalue}, cnonce="{cnonce}"'
233
+
234
+ return f"Digest {base}"
235
+
236
+ def handle_redirect(self, r, **kwargs):
237
+ """Reset num_401_calls counter on redirects."""
238
+ if r.is_redirect:
239
+ self._thread_local.num_401_calls = 1
240
+
241
+ def handle_401(self, r, **kwargs):
242
+ """
243
+ Takes the given response and tries digest-auth, if needed.
244
+
245
+ :rtype: requests.Response
246
+ """
247
+
248
+ # If response is not 4xx, do not auth
249
+ # See https://github.com/psf/requests/issues/3772
250
+ if not 400 <= r.status_code < 500:
251
+ self._thread_local.num_401_calls = 1
252
+ return r
253
+
254
+ if self._thread_local.pos is not None:
255
+ # Rewind the file position indicator of the body to where
256
+ # it was to resend the request.
257
+ r.request.body.seek(self._thread_local.pos)
258
+ s_auth = r.headers.get("www-authenticate", "")
259
+
260
+ if "digest" in s_auth.lower() and self._thread_local.num_401_calls < 2:
261
+ self._thread_local.num_401_calls += 1
262
+ pat = re.compile(r"digest ", flags=re.IGNORECASE)
263
+ self._thread_local.chal = parse_dict_header(pat.sub("", s_auth, count=1))
264
+
265
+ # Consume content and release the original connection
266
+ # to allow our new request to reuse the same one.
267
+ r.content
268
+ r.close()
269
+ prep = r.request.copy()
270
+ extract_cookies_to_jar(prep._cookies, r.request, r.raw)
271
+ prep.prepare_cookies(prep._cookies)
272
+
273
+ prep.headers["Authorization"] = self.build_digest_header(
274
+ prep.method, prep.url
275
+ )
276
+ _r = r.connection.send(prep, **kwargs)
277
+ _r.history.append(r)
278
+ _r.request = prep
279
+
280
+ return _r
281
+
282
+ self._thread_local.num_401_calls = 1
283
+ return r
284
+
285
+ def __call__(self, r):
286
+ # Initialize per-thread state, if needed
287
+ self.init_per_thread_state()
288
+ # If we have a saved nonce, skip the 401
289
+ if self._thread_local.last_nonce:
290
+ r.headers["Authorization"] = self.build_digest_header(r.method, r.url)
291
+ try:
292
+ self._thread_local.pos = r.body.tell()
293
+ except AttributeError:
294
+ # In the case of HTTPDigestAuth being reused and the body of
295
+ # the previous request was a file-like object, pos has the
296
+ # file position of the previous body. Ensure it's set to
297
+ # None.
298
+ self._thread_local.pos = None
299
+ r.register_hook("response", self.handle_401)
300
+ r.register_hook("response", self.handle_redirect)
301
+ self._thread_local.num_401_calls = 1
302
+
303
+ return r
304
+
305
+ def __eq__(self, other):
306
+ return all(
307
+ [
308
+ self.username == getattr(other, "username", None),
309
+ self.password == getattr(other, "password", None),
310
+ ]
311
+ )
312
+
313
+ def __ne__(self, other):
314
+ return not self == other
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/certs.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+
3
+ """
4
+ requests.certs
5
+ ~~~~~~~~~~~~~~
6
+
7
+ This module returns the preferred default CA certificate bundle. There is
8
+ only one — the one from the certifi package.
9
+
10
+ If you are packaging Requests, e.g., for a Linux distribution or a managed
11
+ environment, you can change the definition of where() to return a separately
12
+ packaged CA bundle.
13
+ """
14
+
15
+ import os
16
+
17
+ if "_PIP_STANDALONE_CERT" not in os.environ:
18
+ from pip._vendor.certifi import where
19
+ else:
20
+ def where():
21
+ return os.environ["_PIP_STANDALONE_CERT"]
22
+
23
+ if __name__ == "__main__":
24
+ print(where())
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/cookies.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.cookies
3
+ ~~~~~~~~~~~~~~~~
4
+
5
+ Compatibility code to be able to use `http.cookiejar.CookieJar` with requests.
6
+
7
+ requests.utils imports from here, so be careful with imports.
8
+ """
9
+
10
+ import calendar
11
+ import copy
12
+ import time
13
+
14
+ from ._internal_utils import to_native_string
15
+ from .compat import Morsel, MutableMapping, cookielib, urlparse, urlunparse
16
+
17
+ try:
18
+ import threading
19
+ except ImportError:
20
+ import dummy_threading as threading
21
+
22
+
23
+ class MockRequest:
24
+ """Wraps a `requests.Request` to mimic a `urllib2.Request`.
25
+
26
+ The code in `http.cookiejar.CookieJar` expects this interface in order to correctly
27
+ manage cookie policies, i.e., determine whether a cookie can be set, given the
28
+ domains of the request and the cookie.
29
+
30
+ The original request object is read-only. The client is responsible for collecting
31
+ the new headers via `get_new_headers()` and interpreting them appropriately. You
32
+ probably want `get_cookie_header`, defined below.
33
+ """
34
+
35
+ def __init__(self, request):
36
+ self._r = request
37
+ self._new_headers = {}
38
+ self.type = urlparse(self._r.url).scheme
39
+
40
+ def get_type(self):
41
+ return self.type
42
+
43
+ def get_host(self):
44
+ return urlparse(self._r.url).netloc
45
+
46
+ def get_origin_req_host(self):
47
+ return self.get_host()
48
+
49
+ def get_full_url(self):
50
+ # Only return the response's URL if the user hadn't set the Host
51
+ # header
52
+ if not self._r.headers.get("Host"):
53
+ return self._r.url
54
+ # If they did set it, retrieve it and reconstruct the expected domain
55
+ host = to_native_string(self._r.headers["Host"], encoding="utf-8")
56
+ parsed = urlparse(self._r.url)
57
+ # Reconstruct the URL as we expect it
58
+ return urlunparse(
59
+ [
60
+ parsed.scheme,
61
+ host,
62
+ parsed.path,
63
+ parsed.params,
64
+ parsed.query,
65
+ parsed.fragment,
66
+ ]
67
+ )
68
+
69
+ def is_unverifiable(self):
70
+ return True
71
+
72
+ def has_header(self, name):
73
+ return name in self._r.headers or name in self._new_headers
74
+
75
+ def get_header(self, name, default=None):
76
+ return self._r.headers.get(name, self._new_headers.get(name, default))
77
+
78
+ def add_header(self, key, val):
79
+ """cookiejar has no legitimate use for this method; add it back if you find one."""
80
+ raise NotImplementedError(
81
+ "Cookie headers should be added with add_unredirected_header()"
82
+ )
83
+
84
+ def add_unredirected_header(self, name, value):
85
+ self._new_headers[name] = value
86
+
87
+ def get_new_headers(self):
88
+ return self._new_headers
89
+
90
+ @property
91
+ def unverifiable(self):
92
+ return self.is_unverifiable()
93
+
94
+ @property
95
+ def origin_req_host(self):
96
+ return self.get_origin_req_host()
97
+
98
+ @property
99
+ def host(self):
100
+ return self.get_host()
101
+
102
+
103
+ class MockResponse:
104
+ """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
105
+
106
+ ...what? Basically, expose the parsed HTTP headers from the server response
107
+ the way `http.cookiejar` expects to see them.
108
+ """
109
+
110
+ def __init__(self, headers):
111
+ """Make a MockResponse for `cookiejar` to read.
112
+
113
+ :param headers: a httplib.HTTPMessage or analogous carrying the headers
114
+ """
115
+ self._headers = headers
116
+
117
+ def info(self):
118
+ return self._headers
119
+
120
+ def getheaders(self, name):
121
+ self._headers.getheaders(name)
122
+
123
+
124
+ def extract_cookies_to_jar(jar, request, response):
125
+ """Extract the cookies from the response into a CookieJar.
126
+
127
+ :param jar: http.cookiejar.CookieJar (not necessarily a RequestsCookieJar)
128
+ :param request: our own requests.Request object
129
+ :param response: urllib3.HTTPResponse object
130
+ """
131
+ if not (hasattr(response, "_original_response") and response._original_response):
132
+ return
133
+ # the _original_response field is the wrapped httplib.HTTPResponse object,
134
+ req = MockRequest(request)
135
+ # pull out the HTTPMessage with the headers and put it in the mock:
136
+ res = MockResponse(response._original_response.msg)
137
+ jar.extract_cookies(res, req)
138
+
139
+
140
+ def get_cookie_header(jar, request):
141
+ """
142
+ Produce an appropriate Cookie header string to be sent with `request`, or None.
143
+
144
+ :rtype: str
145
+ """
146
+ r = MockRequest(request)
147
+ jar.add_cookie_header(r)
148
+ return r.get_new_headers().get("Cookie")
149
+
150
+
151
+ def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
152
+ """Unsets a cookie by name, by default over all domains and paths.
153
+
154
+ Wraps CookieJar.clear(), is O(n).
155
+ """
156
+ clearables = []
157
+ for cookie in cookiejar:
158
+ if cookie.name != name:
159
+ continue
160
+ if domain is not None and domain != cookie.domain:
161
+ continue
162
+ if path is not None and path != cookie.path:
163
+ continue
164
+ clearables.append((cookie.domain, cookie.path, cookie.name))
165
+
166
+ for domain, path, name in clearables:
167
+ cookiejar.clear(domain, path, name)
168
+
169
+
170
+ class CookieConflictError(RuntimeError):
171
+ """There are two cookies that meet the criteria specified in the cookie jar.
172
+ Use .get and .set and include domain and path args in order to be more specific.
173
+ """
174
+
175
+
176
+ class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
177
+ """Compatibility class; is a http.cookiejar.CookieJar, but exposes a dict
178
+ interface.
179
+
180
+ This is the CookieJar we create by default for requests and sessions that
181
+ don't specify one, since some clients may expect response.cookies and
182
+ session.cookies to support dict operations.
183
+
184
+ Requests does not use the dict interface internally; it's just for
185
+ compatibility with external client code. All requests code should work
186
+ out of the box with externally provided instances of ``CookieJar``, e.g.
187
+ ``LWPCookieJar`` and ``FileCookieJar``.
188
+
189
+ Unlike a regular CookieJar, this class is pickleable.
190
+
191
+ .. warning:: dictionary operations that are normally O(1) may be O(n).
192
+ """
193
+
194
+ def get(self, name, default=None, domain=None, path=None):
195
+ """Dict-like get() that also supports optional domain and path args in
196
+ order to resolve naming collisions from using one cookie jar over
197
+ multiple domains.
198
+
199
+ .. warning:: operation is O(n), not O(1).
200
+ """
201
+ try:
202
+ return self._find_no_duplicates(name, domain, path)
203
+ except KeyError:
204
+ return default
205
+
206
+ def set(self, name, value, **kwargs):
207
+ """Dict-like set() that also supports optional domain and path args in
208
+ order to resolve naming collisions from using one cookie jar over
209
+ multiple domains.
210
+ """
211
+ # support client code that unsets cookies by assignment of a None value:
212
+ if value is None:
213
+ remove_cookie_by_name(
214
+ self, name, domain=kwargs.get("domain"), path=kwargs.get("path")
215
+ )
216
+ return
217
+
218
+ if isinstance(value, Morsel):
219
+ c = morsel_to_cookie(value)
220
+ else:
221
+ c = create_cookie(name, value, **kwargs)
222
+ self.set_cookie(c)
223
+ return c
224
+
225
+ def iterkeys(self):
226
+ """Dict-like iterkeys() that returns an iterator of names of cookies
227
+ from the jar.
228
+
229
+ .. seealso:: itervalues() and iteritems().
230
+ """
231
+ for cookie in iter(self):
232
+ yield cookie.name
233
+
234
+ def keys(self):
235
+ """Dict-like keys() that returns a list of names of cookies from the
236
+ jar.
237
+
238
+ .. seealso:: values() and items().
239
+ """
240
+ return list(self.iterkeys())
241
+
242
+ def itervalues(self):
243
+ """Dict-like itervalues() that returns an iterator of values of cookies
244
+ from the jar.
245
+
246
+ .. seealso:: iterkeys() and iteritems().
247
+ """
248
+ for cookie in iter(self):
249
+ yield cookie.value
250
+
251
+ def values(self):
252
+ """Dict-like values() that returns a list of values of cookies from the
253
+ jar.
254
+
255
+ .. seealso:: keys() and items().
256
+ """
257
+ return list(self.itervalues())
258
+
259
+ def iteritems(self):
260
+ """Dict-like iteritems() that returns an iterator of name-value tuples
261
+ from the jar.
262
+
263
+ .. seealso:: iterkeys() and itervalues().
264
+ """
265
+ for cookie in iter(self):
266
+ yield cookie.name, cookie.value
267
+
268
+ def items(self):
269
+ """Dict-like items() that returns a list of name-value tuples from the
270
+ jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
271
+ vanilla python dict of key value pairs.
272
+
273
+ .. seealso:: keys() and values().
274
+ """
275
+ return list(self.iteritems())
276
+
277
+ def list_domains(self):
278
+ """Utility method to list all the domains in the jar."""
279
+ domains = []
280
+ for cookie in iter(self):
281
+ if cookie.domain not in domains:
282
+ domains.append(cookie.domain)
283
+ return domains
284
+
285
+ def list_paths(self):
286
+ """Utility method to list all the paths in the jar."""
287
+ paths = []
288
+ for cookie in iter(self):
289
+ if cookie.path not in paths:
290
+ paths.append(cookie.path)
291
+ return paths
292
+
293
+ def multiple_domains(self):
294
+ """Returns True if there are multiple domains in the jar.
295
+ Returns False otherwise.
296
+
297
+ :rtype: bool
298
+ """
299
+ domains = []
300
+ for cookie in iter(self):
301
+ if cookie.domain is not None and cookie.domain in domains:
302
+ return True
303
+ domains.append(cookie.domain)
304
+ return False # there is only one domain in jar
305
+
306
+ def get_dict(self, domain=None, path=None):
307
+ """Takes as an argument an optional domain and path and returns a plain
308
+ old Python dict of name-value pairs of cookies that meet the
309
+ requirements.
310
+
311
+ :rtype: dict
312
+ """
313
+ dictionary = {}
314
+ for cookie in iter(self):
315
+ if (domain is None or cookie.domain == domain) and (
316
+ path is None or cookie.path == path
317
+ ):
318
+ dictionary[cookie.name] = cookie.value
319
+ return dictionary
320
+
321
+ def __contains__(self, name):
322
+ try:
323
+ return super().__contains__(name)
324
+ except CookieConflictError:
325
+ return True
326
+
327
+ def __getitem__(self, name):
328
+ """Dict-like __getitem__() for compatibility with client code. Throws
329
+ exception if there are more than one cookie with name. In that case,
330
+ use the more explicit get() method instead.
331
+
332
+ .. warning:: operation is O(n), not O(1).
333
+ """
334
+ return self._find_no_duplicates(name)
335
+
336
+ def __setitem__(self, name, value):
337
+ """Dict-like __setitem__ for compatibility with client code. Throws
338
+ exception if there is already a cookie of that name in the jar. In that
339
+ case, use the more explicit set() method instead.
340
+ """
341
+ self.set(name, value)
342
+
343
+ def __delitem__(self, name):
344
+ """Deletes a cookie given a name. Wraps ``http.cookiejar.CookieJar``'s
345
+ ``remove_cookie_by_name()``.
346
+ """
347
+ remove_cookie_by_name(self, name)
348
+
349
+ def set_cookie(self, cookie, *args, **kwargs):
350
+ if (
351
+ hasattr(cookie.value, "startswith")
352
+ and cookie.value.startswith('"')
353
+ and cookie.value.endswith('"')
354
+ ):
355
+ cookie.value = cookie.value.replace('\\"', "")
356
+ return super().set_cookie(cookie, *args, **kwargs)
357
+
358
+ def update(self, other):
359
+ """Updates this jar with cookies from another CookieJar or dict-like"""
360
+ if isinstance(other, cookielib.CookieJar):
361
+ for cookie in other:
362
+ self.set_cookie(copy.copy(cookie))
363
+ else:
364
+ super().update(other)
365
+
366
+ def _find(self, name, domain=None, path=None):
367
+ """Requests uses this method internally to get cookie values.
368
+
369
+ If there are conflicting cookies, _find arbitrarily chooses one.
370
+ See _find_no_duplicates if you want an exception thrown if there are
371
+ conflicting cookies.
372
+
373
+ :param name: a string containing name of cookie
374
+ :param domain: (optional) string containing domain of cookie
375
+ :param path: (optional) string containing path of cookie
376
+ :return: cookie.value
377
+ """
378
+ for cookie in iter(self):
379
+ if cookie.name == name:
380
+ if domain is None or cookie.domain == domain:
381
+ if path is None or cookie.path == path:
382
+ return cookie.value
383
+
384
+ raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
385
+
386
+ def _find_no_duplicates(self, name, domain=None, path=None):
387
+ """Both ``__get_item__`` and ``get`` call this function: it's never
388
+ used elsewhere in Requests.
389
+
390
+ :param name: a string containing name of cookie
391
+ :param domain: (optional) string containing domain of cookie
392
+ :param path: (optional) string containing path of cookie
393
+ :raises KeyError: if cookie is not found
394
+ :raises CookieConflictError: if there are multiple cookies
395
+ that match name and optionally domain and path
396
+ :return: cookie.value
397
+ """
398
+ toReturn = None
399
+ for cookie in iter(self):
400
+ if cookie.name == name:
401
+ if domain is None or cookie.domain == domain:
402
+ if path is None or cookie.path == path:
403
+ if toReturn is not None:
404
+ # if there are multiple cookies that meet passed in criteria
405
+ raise CookieConflictError(
406
+ f"There are multiple cookies with name, {name!r}"
407
+ )
408
+ # we will eventually return this as long as no cookie conflict
409
+ toReturn = cookie.value
410
+
411
+ if toReturn:
412
+ return toReturn
413
+ raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")
414
+
415
+ def __getstate__(self):
416
+ """Unlike a normal CookieJar, this class is pickleable."""
417
+ state = self.__dict__.copy()
418
+ # remove the unpickleable RLock object
419
+ state.pop("_cookies_lock")
420
+ return state
421
+
422
+ def __setstate__(self, state):
423
+ """Unlike a normal CookieJar, this class is pickleable."""
424
+ self.__dict__.update(state)
425
+ if "_cookies_lock" not in self.__dict__:
426
+ self._cookies_lock = threading.RLock()
427
+
428
+ def copy(self):
429
+ """Return a copy of this RequestsCookieJar."""
430
+ new_cj = RequestsCookieJar()
431
+ new_cj.set_policy(self.get_policy())
432
+ new_cj.update(self)
433
+ return new_cj
434
+
435
+ def get_policy(self):
436
+ """Return the CookiePolicy instance used."""
437
+ return self._policy
438
+
439
+
440
+ def _copy_cookie_jar(jar):
441
+ if jar is None:
442
+ return None
443
+
444
+ if hasattr(jar, "copy"):
445
+ # We're dealing with an instance of RequestsCookieJar
446
+ return jar.copy()
447
+ # We're dealing with a generic CookieJar instance
448
+ new_jar = copy.copy(jar)
449
+ new_jar.clear()
450
+ for cookie in jar:
451
+ new_jar.set_cookie(copy.copy(cookie))
452
+ return new_jar
453
+
454
+
455
+ def create_cookie(name, value, **kwargs):
456
+ """Make a cookie from underspecified parameters.
457
+
458
+ By default, the pair of `name` and `value` will be set for the domain ''
459
+ and sent on every request (this is sometimes called a "supercookie").
460
+ """
461
+ result = {
462
+ "version": 0,
463
+ "name": name,
464
+ "value": value,
465
+ "port": None,
466
+ "domain": "",
467
+ "path": "/",
468
+ "secure": False,
469
+ "expires": None,
470
+ "discard": True,
471
+ "comment": None,
472
+ "comment_url": None,
473
+ "rest": {"HttpOnly": None},
474
+ "rfc2109": False,
475
+ }
476
+
477
+ badargs = set(kwargs) - set(result)
478
+ if badargs:
479
+ raise TypeError(
480
+ f"create_cookie() got unexpected keyword arguments: {list(badargs)}"
481
+ )
482
+
483
+ result.update(kwargs)
484
+ result["port_specified"] = bool(result["port"])
485
+ result["domain_specified"] = bool(result["domain"])
486
+ result["domain_initial_dot"] = result["domain"].startswith(".")
487
+ result["path_specified"] = bool(result["path"])
488
+
489
+ return cookielib.Cookie(**result)
490
+
491
+
492
+ def morsel_to_cookie(morsel):
493
+ """Convert a Morsel object into a Cookie containing the one k/v pair."""
494
+
495
+ expires = None
496
+ if morsel["max-age"]:
497
+ try:
498
+ expires = int(time.time() + int(morsel["max-age"]))
499
+ except ValueError:
500
+ raise TypeError(f"max-age: {morsel['max-age']} must be integer")
501
+ elif morsel["expires"]:
502
+ time_template = "%a, %d-%b-%Y %H:%M:%S GMT"
503
+ expires = calendar.timegm(time.strptime(morsel["expires"], time_template))
504
+ return create_cookie(
505
+ comment=morsel["comment"],
506
+ comment_url=bool(morsel["comment"]),
507
+ discard=False,
508
+ domain=morsel["domain"],
509
+ expires=expires,
510
+ name=morsel.key,
511
+ path=morsel["path"],
512
+ port=None,
513
+ rest={"HttpOnly": morsel["httponly"]},
514
+ rfc2109=False,
515
+ secure=bool(morsel["secure"]),
516
+ value=morsel.value,
517
+ version=morsel["version"] or 0,
518
+ )
519
+
520
+
521
+ def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
522
+ """Returns a CookieJar from a key/value dictionary.
523
+
524
+ :param cookie_dict: Dict of key/values to insert into CookieJar.
525
+ :param cookiejar: (optional) A cookiejar to add the cookies to.
526
+ :param overwrite: (optional) If False, will not replace cookies
527
+ already in the jar with new ones.
528
+ :rtype: CookieJar
529
+ """
530
+ if cookiejar is None:
531
+ cookiejar = RequestsCookieJar()
532
+
533
+ if cookie_dict is not None:
534
+ names_from_jar = [cookie.name for cookie in cookiejar]
535
+ for name in cookie_dict:
536
+ if overwrite or (name not in names_from_jar):
537
+ cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
538
+
539
+ return cookiejar
540
+
541
+
542
+ def merge_cookies(cookiejar, cookies):
543
+ """Add cookies to cookiejar and returns a merged CookieJar.
544
+
545
+ :param cookiejar: CookieJar object to add the cookies to.
546
+ :param cookies: Dictionary or CookieJar object to be added.
547
+ :rtype: CookieJar
548
+ """
549
+ if not isinstance(cookiejar, cookielib.CookieJar):
550
+ raise ValueError("You can only merge into CookieJar")
551
+
552
+ if isinstance(cookies, dict):
553
+ cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=False)
554
+ elif isinstance(cookies, cookielib.CookieJar):
555
+ try:
556
+ cookiejar.update(cookies)
557
+ except AttributeError:
558
+ for cookie_in_jar in cookies:
559
+ cookiejar.set_cookie(cookie_in_jar)
560
+
561
+ return cookiejar
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/exceptions.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.exceptions
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ This module contains the set of Requests' exceptions.
6
+ """
7
+ from pip._vendor.urllib3.exceptions import HTTPError as BaseHTTPError
8
+
9
+ from .compat import JSONDecodeError as CompatJSONDecodeError
10
+
11
+
12
+ class RequestException(IOError):
13
+ """There was an ambiguous exception that occurred while handling your
14
+ request.
15
+ """
16
+
17
+ def __init__(self, *args, **kwargs):
18
+ """Initialize RequestException with `request` and `response` objects."""
19
+ response = kwargs.pop("response", None)
20
+ self.response = response
21
+ self.request = kwargs.pop("request", None)
22
+ if response is not None and not self.request and hasattr(response, "request"):
23
+ self.request = self.response.request
24
+ super().__init__(*args, **kwargs)
25
+
26
+
27
+ class InvalidJSONError(RequestException):
28
+ """A JSON error occurred."""
29
+
30
+
31
+ class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):
32
+ """Couldn't decode the text into json"""
33
+
34
+ def __init__(self, *args, **kwargs):
35
+ """
36
+ Construct the JSONDecodeError instance first with all
37
+ args. Then use it's args to construct the IOError so that
38
+ the json specific args aren't used as IOError specific args
39
+ and the error message from JSONDecodeError is preserved.
40
+ """
41
+ CompatJSONDecodeError.__init__(self, *args)
42
+ InvalidJSONError.__init__(self, *self.args, **kwargs)
43
+
44
+ def __reduce__(self):
45
+ """
46
+ The __reduce__ method called when pickling the object must
47
+ be the one from the JSONDecodeError (be it json/simplejson)
48
+ as it expects all the arguments for instantiation, not just
49
+ one like the IOError, and the MRO would by default call the
50
+ __reduce__ method from the IOError due to the inheritance order.
51
+ """
52
+ return CompatJSONDecodeError.__reduce__(self)
53
+
54
+
55
+ class HTTPError(RequestException):
56
+ """An HTTP error occurred."""
57
+
58
+
59
+ class ConnectionError(RequestException):
60
+ """A Connection error occurred."""
61
+
62
+
63
+ class ProxyError(ConnectionError):
64
+ """A proxy error occurred."""
65
+
66
+
67
+ class SSLError(ConnectionError):
68
+ """An SSL error occurred."""
69
+
70
+
71
+ class Timeout(RequestException):
72
+ """The request timed out.
73
+
74
+ Catching this error will catch both
75
+ :exc:`~requests.exceptions.ConnectTimeout` and
76
+ :exc:`~requests.exceptions.ReadTimeout` errors.
77
+ """
78
+
79
+
80
+ class ConnectTimeout(ConnectionError, Timeout):
81
+ """The request timed out while trying to connect to the remote server.
82
+
83
+ Requests that produced this error are safe to retry.
84
+ """
85
+
86
+
87
+ class ReadTimeout(Timeout):
88
+ """The server did not send any data in the allotted amount of time."""
89
+
90
+
91
+ class URLRequired(RequestException):
92
+ """A valid URL is required to make a request."""
93
+
94
+
95
+ class TooManyRedirects(RequestException):
96
+ """Too many redirects."""
97
+
98
+
99
+ class MissingSchema(RequestException, ValueError):
100
+ """The URL scheme (e.g. http or https) is missing."""
101
+
102
+
103
+ class InvalidSchema(RequestException, ValueError):
104
+ """The URL scheme provided is either invalid or unsupported."""
105
+
106
+
107
+ class InvalidURL(RequestException, ValueError):
108
+ """The URL provided was somehow invalid."""
109
+
110
+
111
+ class InvalidHeader(RequestException, ValueError):
112
+ """The header value provided was somehow invalid."""
113
+
114
+
115
+ class InvalidProxyURL(InvalidURL):
116
+ """The proxy URL provided is invalid."""
117
+
118
+
119
+ class ChunkedEncodingError(RequestException):
120
+ """The server declared chunked encoding but sent an invalid chunk."""
121
+
122
+
123
+ class ContentDecodingError(RequestException, BaseHTTPError):
124
+ """Failed to decode response content."""
125
+
126
+
127
+ class StreamConsumedError(RequestException, TypeError):
128
+ """The content for this response was already consumed."""
129
+
130
+
131
+ class RetryError(RequestException):
132
+ """Custom retries logic failed"""
133
+
134
+
135
+ class UnrewindableBodyError(RequestException):
136
+ """Requests encountered an error when trying to rewind a body."""
137
+
138
+
139
+ # Warnings
140
+
141
+
142
+ class RequestsWarning(Warning):
143
+ """Base warning for Requests."""
144
+
145
+
146
+ class FileModeWarning(RequestsWarning, DeprecationWarning):
147
+ """A file was opened in text mode, but Requests determined its binary length."""
148
+
149
+
150
+ class RequestsDependencyWarning(RequestsWarning):
151
+ """An imported dependency doesn't match the expected version range."""
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/help.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module containing bug report helper(s)."""
2
+
3
+ import json
4
+ import platform
5
+ import ssl
6
+ import sys
7
+
8
+ from pip._vendor import idna
9
+ from pip._vendor import urllib3
10
+
11
+ from . import __version__ as requests_version
12
+
13
+ charset_normalizer = None
14
+ chardet = None
15
+
16
+ try:
17
+ from pip._vendor.urllib3.contrib import pyopenssl
18
+ except ImportError:
19
+ pyopenssl = None
20
+ OpenSSL = None
21
+ cryptography = None
22
+ else:
23
+ import cryptography
24
+ import OpenSSL
25
+
26
+
27
+ def _implementation():
28
+ """Return a dict with the Python implementation and version.
29
+
30
+ Provide both the name and the version of the Python implementation
31
+ currently running. For example, on CPython 3.10.3 it will return
32
+ {'name': 'CPython', 'version': '3.10.3'}.
33
+
34
+ This function works best on CPython and PyPy: in particular, it probably
35
+ doesn't work for Jython or IronPython. Future investigation should be done
36
+ to work out the correct shape of the code for those platforms.
37
+ """
38
+ implementation = platform.python_implementation()
39
+
40
+ if implementation == "CPython":
41
+ implementation_version = platform.python_version()
42
+ elif implementation == "PyPy":
43
+ implementation_version = "{}.{}.{}".format(
44
+ sys.pypy_version_info.major,
45
+ sys.pypy_version_info.minor,
46
+ sys.pypy_version_info.micro,
47
+ )
48
+ if sys.pypy_version_info.releaselevel != "final":
49
+ implementation_version = "".join(
50
+ [implementation_version, sys.pypy_version_info.releaselevel]
51
+ )
52
+ elif implementation == "Jython":
53
+ implementation_version = platform.python_version() # Complete Guess
54
+ elif implementation == "IronPython":
55
+ implementation_version = platform.python_version() # Complete Guess
56
+ else:
57
+ implementation_version = "Unknown"
58
+
59
+ return {"name": implementation, "version": implementation_version}
60
+
61
+
62
+ def info():
63
+ """Generate information for a bug report."""
64
+ try:
65
+ platform_info = {
66
+ "system": platform.system(),
67
+ "release": platform.release(),
68
+ }
69
+ except OSError:
70
+ platform_info = {
71
+ "system": "Unknown",
72
+ "release": "Unknown",
73
+ }
74
+
75
+ implementation_info = _implementation()
76
+ urllib3_info = {"version": urllib3.__version__}
77
+ charset_normalizer_info = {"version": None}
78
+ chardet_info = {"version": None}
79
+ if charset_normalizer:
80
+ charset_normalizer_info = {"version": charset_normalizer.__version__}
81
+ if chardet:
82
+ chardet_info = {"version": chardet.__version__}
83
+
84
+ pyopenssl_info = {
85
+ "version": None,
86
+ "openssl_version": "",
87
+ }
88
+ if OpenSSL:
89
+ pyopenssl_info = {
90
+ "version": OpenSSL.__version__,
91
+ "openssl_version": f"{OpenSSL.SSL.OPENSSL_VERSION_NUMBER:x}",
92
+ }
93
+ cryptography_info = {
94
+ "version": getattr(cryptography, "__version__", ""),
95
+ }
96
+ idna_info = {
97
+ "version": getattr(idna, "__version__", ""),
98
+ }
99
+
100
+ system_ssl = ssl.OPENSSL_VERSION_NUMBER
101
+ system_ssl_info = {"version": f"{system_ssl:x}" if system_ssl is not None else ""}
102
+
103
+ return {
104
+ "platform": platform_info,
105
+ "implementation": implementation_info,
106
+ "system_ssl": system_ssl_info,
107
+ "using_pyopenssl": pyopenssl is not None,
108
+ "using_charset_normalizer": chardet is None,
109
+ "pyOpenSSL": pyopenssl_info,
110
+ "urllib3": urllib3_info,
111
+ "chardet": chardet_info,
112
+ "charset_normalizer": charset_normalizer_info,
113
+ "cryptography": cryptography_info,
114
+ "idna": idna_info,
115
+ "requests": {
116
+ "version": requests_version,
117
+ },
118
+ }
119
+
120
+
121
+ def main():
122
+ """Pretty-print the bug information as JSON."""
123
+ print(json.dumps(info(), sort_keys=True, indent=2))
124
+
125
+
126
+ if __name__ == "__main__":
127
+ main()
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/models.py ADDED
@@ -0,0 +1,1037 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.models
3
+ ~~~~~~~~~~~~~~~
4
+
5
+ This module contains the primary objects that power Requests.
6
+ """
7
+
8
+ import datetime
9
+
10
+ # Import encoding now, to avoid implicit import later.
11
+ # Implicit import within threads may cause LookupError when standard library is in a ZIP,
12
+ # such as in Embedded Python. See https://github.com/psf/requests/issues/3578.
13
+ import encodings.idna # noqa: F401
14
+ from io import UnsupportedOperation
15
+
16
+ from pip._vendor.urllib3.exceptions import (
17
+ DecodeError,
18
+ LocationParseError,
19
+ ProtocolError,
20
+ ReadTimeoutError,
21
+ SSLError,
22
+ )
23
+ from pip._vendor.urllib3.fields import RequestField
24
+ from pip._vendor.urllib3.filepost import encode_multipart_formdata
25
+ from pip._vendor.urllib3.util import parse_url
26
+
27
+ from ._internal_utils import to_native_string, unicode_is_ascii
28
+ from .auth import HTTPBasicAuth
29
+ from .compat import (
30
+ Callable,
31
+ JSONDecodeError,
32
+ Mapping,
33
+ basestring,
34
+ builtin_str,
35
+ chardet,
36
+ cookielib,
37
+ )
38
+ from .compat import json as complexjson
39
+ from .compat import urlencode, urlsplit, urlunparse
40
+ from .cookies import _copy_cookie_jar, cookiejar_from_dict, get_cookie_header
41
+ from .exceptions import (
42
+ ChunkedEncodingError,
43
+ ConnectionError,
44
+ ContentDecodingError,
45
+ HTTPError,
46
+ InvalidJSONError,
47
+ InvalidURL,
48
+ )
49
+ from .exceptions import JSONDecodeError as RequestsJSONDecodeError
50
+ from .exceptions import MissingSchema
51
+ from .exceptions import SSLError as RequestsSSLError
52
+ from .exceptions import StreamConsumedError
53
+ from .hooks import default_hooks
54
+ from .status_codes import codes
55
+ from .structures import CaseInsensitiveDict
56
+ from .utils import (
57
+ check_header_validity,
58
+ get_auth_from_url,
59
+ guess_filename,
60
+ guess_json_utf,
61
+ iter_slices,
62
+ parse_header_links,
63
+ requote_uri,
64
+ stream_decode_response_unicode,
65
+ super_len,
66
+ to_key_val_list,
67
+ )
68
+
69
+ #: The set of HTTP status codes that indicate an automatically
70
+ #: processable redirect.
71
+ REDIRECT_STATI = (
72
+ codes.moved, # 301
73
+ codes.found, # 302
74
+ codes.other, # 303
75
+ codes.temporary_redirect, # 307
76
+ codes.permanent_redirect, # 308
77
+ )
78
+
79
+ DEFAULT_REDIRECT_LIMIT = 30
80
+ CONTENT_CHUNK_SIZE = 10 * 1024
81
+ ITER_CHUNK_SIZE = 512
82
+
83
+
84
+ class RequestEncodingMixin:
85
+ @property
86
+ def path_url(self):
87
+ """Build the path URL to use."""
88
+
89
+ url = []
90
+
91
+ p = urlsplit(self.url)
92
+
93
+ path = p.path
94
+ if not path:
95
+ path = "/"
96
+
97
+ url.append(path)
98
+
99
+ query = p.query
100
+ if query:
101
+ url.append("?")
102
+ url.append(query)
103
+
104
+ return "".join(url)
105
+
106
+ @staticmethod
107
+ def _encode_params(data):
108
+ """Encode parameters in a piece of data.
109
+
110
+ Will successfully encode parameters when passed as a dict or a list of
111
+ 2-tuples. Order is retained if data is a list of 2-tuples but arbitrary
112
+ if parameters are supplied as a dict.
113
+ """
114
+
115
+ if isinstance(data, (str, bytes)):
116
+ return data
117
+ elif hasattr(data, "read"):
118
+ return data
119
+ elif hasattr(data, "__iter__"):
120
+ result = []
121
+ for k, vs in to_key_val_list(data):
122
+ if isinstance(vs, basestring) or not hasattr(vs, "__iter__"):
123
+ vs = [vs]
124
+ for v in vs:
125
+ if v is not None:
126
+ result.append(
127
+ (
128
+ k.encode("utf-8") if isinstance(k, str) else k,
129
+ v.encode("utf-8") if isinstance(v, str) else v,
130
+ )
131
+ )
132
+ return urlencode(result, doseq=True)
133
+ else:
134
+ return data
135
+
136
+ @staticmethod
137
+ def _encode_files(files, data):
138
+ """Build the body for a multipart/form-data request.
139
+
140
+ Will successfully encode files when passed as a dict or a list of
141
+ tuples. Order is retained if data is a list of tuples but arbitrary
142
+ if parameters are supplied as a dict.
143
+ The tuples may be 2-tuples (filename, fileobj), 3-tuples (filename, fileobj, contentype)
144
+ or 4-tuples (filename, fileobj, contentype, custom_headers).
145
+ """
146
+ if not files:
147
+ raise ValueError("Files must be provided.")
148
+ elif isinstance(data, basestring):
149
+ raise ValueError("Data must not be a string.")
150
+
151
+ new_fields = []
152
+ fields = to_key_val_list(data or {})
153
+ files = to_key_val_list(files or {})
154
+
155
+ for field, val in fields:
156
+ if isinstance(val, basestring) or not hasattr(val, "__iter__"):
157
+ val = [val]
158
+ for v in val:
159
+ if v is not None:
160
+ # Don't call str() on bytestrings: in Py3 it all goes wrong.
161
+ if not isinstance(v, bytes):
162
+ v = str(v)
163
+
164
+ new_fields.append(
165
+ (
166
+ field.decode("utf-8")
167
+ if isinstance(field, bytes)
168
+ else field,
169
+ v.encode("utf-8") if isinstance(v, str) else v,
170
+ )
171
+ )
172
+
173
+ for k, v in files:
174
+ # support for explicit filename
175
+ ft = None
176
+ fh = None
177
+ if isinstance(v, (tuple, list)):
178
+ if len(v) == 2:
179
+ fn, fp = v
180
+ elif len(v) == 3:
181
+ fn, fp, ft = v
182
+ else:
183
+ fn, fp, ft, fh = v
184
+ else:
185
+ fn = guess_filename(v) or k
186
+ fp = v
187
+
188
+ if isinstance(fp, (str, bytes, bytearray)):
189
+ fdata = fp
190
+ elif hasattr(fp, "read"):
191
+ fdata = fp.read()
192
+ elif fp is None:
193
+ continue
194
+ else:
195
+ fdata = fp
196
+
197
+ rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)
198
+ rf.make_multipart(content_type=ft)
199
+ new_fields.append(rf)
200
+
201
+ body, content_type = encode_multipart_formdata(new_fields)
202
+
203
+ return body, content_type
204
+
205
+
206
+ class RequestHooksMixin:
207
+ def register_hook(self, event, hook):
208
+ """Properly register a hook."""
209
+
210
+ if event not in self.hooks:
211
+ raise ValueError(f'Unsupported event specified, with event name "{event}"')
212
+
213
+ if isinstance(hook, Callable):
214
+ self.hooks[event].append(hook)
215
+ elif hasattr(hook, "__iter__"):
216
+ self.hooks[event].extend(h for h in hook if isinstance(h, Callable))
217
+
218
+ def deregister_hook(self, event, hook):
219
+ """Deregister a previously registered hook.
220
+ Returns True if the hook existed, False if not.
221
+ """
222
+
223
+ try:
224
+ self.hooks[event].remove(hook)
225
+ return True
226
+ except ValueError:
227
+ return False
228
+
229
+
230
+ class Request(RequestHooksMixin):
231
+ """A user-created :class:`Request <Request>` object.
232
+
233
+ Used to prepare a :class:`PreparedRequest <PreparedRequest>`, which is sent to the server.
234
+
235
+ :param method: HTTP method to use.
236
+ :param url: URL to send.
237
+ :param headers: dictionary of headers to send.
238
+ :param files: dictionary of {filename: fileobject} files to multipart upload.
239
+ :param data: the body to attach to the request. If a dictionary or
240
+ list of tuples ``[(key, value)]`` is provided, form-encoding will
241
+ take place.
242
+ :param json: json for the body to attach to the request (if files or data is not specified).
243
+ :param params: URL parameters to append to the URL. If a dictionary or
244
+ list of tuples ``[(key, value)]`` is provided, form-encoding will
245
+ take place.
246
+ :param auth: Auth handler or (user, pass) tuple.
247
+ :param cookies: dictionary or CookieJar of cookies to attach to this request.
248
+ :param hooks: dictionary of callback hooks, for internal usage.
249
+
250
+ Usage::
251
+
252
+ >>> import requests
253
+ >>> req = requests.Request('GET', 'https://httpbin.org/get')
254
+ >>> req.prepare()
255
+ <PreparedRequest [GET]>
256
+ """
257
+
258
+ def __init__(
259
+ self,
260
+ method=None,
261
+ url=None,
262
+ headers=None,
263
+ files=None,
264
+ data=None,
265
+ params=None,
266
+ auth=None,
267
+ cookies=None,
268
+ hooks=None,
269
+ json=None,
270
+ ):
271
+ # Default empty dicts for dict params.
272
+ data = [] if data is None else data
273
+ files = [] if files is None else files
274
+ headers = {} if headers is None else headers
275
+ params = {} if params is None else params
276
+ hooks = {} if hooks is None else hooks
277
+
278
+ self.hooks = default_hooks()
279
+ for k, v in list(hooks.items()):
280
+ self.register_hook(event=k, hook=v)
281
+
282
+ self.method = method
283
+ self.url = url
284
+ self.headers = headers
285
+ self.files = files
286
+ self.data = data
287
+ self.json = json
288
+ self.params = params
289
+ self.auth = auth
290
+ self.cookies = cookies
291
+
292
+ def __repr__(self):
293
+ return f"<Request [{self.method}]>"
294
+
295
+ def prepare(self):
296
+ """Constructs a :class:`PreparedRequest <PreparedRequest>` for transmission and returns it."""
297
+ p = PreparedRequest()
298
+ p.prepare(
299
+ method=self.method,
300
+ url=self.url,
301
+ headers=self.headers,
302
+ files=self.files,
303
+ data=self.data,
304
+ json=self.json,
305
+ params=self.params,
306
+ auth=self.auth,
307
+ cookies=self.cookies,
308
+ hooks=self.hooks,
309
+ )
310
+ return p
311
+
312
+
313
+ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):
314
+ """The fully mutable :class:`PreparedRequest <PreparedRequest>` object,
315
+ containing the exact bytes that will be sent to the server.
316
+
317
+ Instances are generated from a :class:`Request <Request>` object, and
318
+ should not be instantiated manually; doing so may produce undesirable
319
+ effects.
320
+
321
+ Usage::
322
+
323
+ >>> import requests
324
+ >>> req = requests.Request('GET', 'https://httpbin.org/get')
325
+ >>> r = req.prepare()
326
+ >>> r
327
+ <PreparedRequest [GET]>
328
+
329
+ >>> s = requests.Session()
330
+ >>> s.send(r)
331
+ <Response [200]>
332
+ """
333
+
334
+ def __init__(self):
335
+ #: HTTP verb to send to the server.
336
+ self.method = None
337
+ #: HTTP URL to send the request to.
338
+ self.url = None
339
+ #: dictionary of HTTP headers.
340
+ self.headers = None
341
+ # The `CookieJar` used to create the Cookie header will be stored here
342
+ # after prepare_cookies is called
343
+ self._cookies = None
344
+ #: request body to send to the server.
345
+ self.body = None
346
+ #: dictionary of callback hooks, for internal usage.
347
+ self.hooks = default_hooks()
348
+ #: integer denoting starting position of a readable file-like body.
349
+ self._body_position = None
350
+
351
+ def prepare(
352
+ self,
353
+ method=None,
354
+ url=None,
355
+ headers=None,
356
+ files=None,
357
+ data=None,
358
+ params=None,
359
+ auth=None,
360
+ cookies=None,
361
+ hooks=None,
362
+ json=None,
363
+ ):
364
+ """Prepares the entire request with the given parameters."""
365
+
366
+ self.prepare_method(method)
367
+ self.prepare_url(url, params)
368
+ self.prepare_headers(headers)
369
+ self.prepare_cookies(cookies)
370
+ self.prepare_body(data, files, json)
371
+ self.prepare_auth(auth, url)
372
+
373
+ # Note that prepare_auth must be last to enable authentication schemes
374
+ # such as OAuth to work on a fully prepared request.
375
+
376
+ # This MUST go after prepare_auth. Authenticators could add a hook
377
+ self.prepare_hooks(hooks)
378
+
379
+ def __repr__(self):
380
+ return f"<PreparedRequest [{self.method}]>"
381
+
382
+ def copy(self):
383
+ p = PreparedRequest()
384
+ p.method = self.method
385
+ p.url = self.url
386
+ p.headers = self.headers.copy() if self.headers is not None else None
387
+ p._cookies = _copy_cookie_jar(self._cookies)
388
+ p.body = self.body
389
+ p.hooks = self.hooks
390
+ p._body_position = self._body_position
391
+ return p
392
+
393
+ def prepare_method(self, method):
394
+ """Prepares the given HTTP method."""
395
+ self.method = method
396
+ if self.method is not None:
397
+ self.method = to_native_string(self.method.upper())
398
+
399
+ @staticmethod
400
+ def _get_idna_encoded_host(host):
401
+ from pip._vendor import idna
402
+
403
+ try:
404
+ host = idna.encode(host, uts46=True).decode("utf-8")
405
+ except idna.IDNAError:
406
+ raise UnicodeError
407
+ return host
408
+
409
+ def prepare_url(self, url, params):
410
+ """Prepares the given HTTP URL."""
411
+ #: Accept objects that have string representations.
412
+ #: We're unable to blindly call unicode/str functions
413
+ #: as this will include the bytestring indicator (b'')
414
+ #: on python 3.x.
415
+ #: https://github.com/psf/requests/pull/2238
416
+ if isinstance(url, bytes):
417
+ url = url.decode("utf8")
418
+ else:
419
+ url = str(url)
420
+
421
+ # Remove leading whitespaces from url
422
+ url = url.lstrip()
423
+
424
+ # Don't do any URL preparation for non-HTTP schemes like `mailto`,
425
+ # `data` etc to work around exceptions from `url_parse`, which
426
+ # handles RFC 3986 only.
427
+ if ":" in url and not url.lower().startswith("http"):
428
+ self.url = url
429
+ return
430
+
431
+ # Support for unicode domain names and paths.
432
+ try:
433
+ scheme, auth, host, port, path, query, fragment = parse_url(url)
434
+ except LocationParseError as e:
435
+ raise InvalidURL(*e.args)
436
+
437
+ if not scheme:
438
+ raise MissingSchema(
439
+ f"Invalid URL {url!r}: No scheme supplied. "
440
+ f"Perhaps you meant https://{url}?"
441
+ )
442
+
443
+ if not host:
444
+ raise InvalidURL(f"Invalid URL {url!r}: No host supplied")
445
+
446
+ # In general, we want to try IDNA encoding the hostname if the string contains
447
+ # non-ASCII characters. This allows users to automatically get the correct IDNA
448
+ # behaviour. For strings containing only ASCII characters, we need to also verify
449
+ # it doesn't start with a wildcard (*), before allowing the unencoded hostname.
450
+ if not unicode_is_ascii(host):
451
+ try:
452
+ host = self._get_idna_encoded_host(host)
453
+ except UnicodeError:
454
+ raise InvalidURL("URL has an invalid label.")
455
+ elif host.startswith(("*", ".")):
456
+ raise InvalidURL("URL has an invalid label.")
457
+
458
+ # Carefully reconstruct the network location
459
+ netloc = auth or ""
460
+ if netloc:
461
+ netloc += "@"
462
+ netloc += host
463
+ if port:
464
+ netloc += f":{port}"
465
+
466
+ # Bare domains aren't valid URLs.
467
+ if not path:
468
+ path = "/"
469
+
470
+ if isinstance(params, (str, bytes)):
471
+ params = to_native_string(params)
472
+
473
+ enc_params = self._encode_params(params)
474
+ if enc_params:
475
+ if query:
476
+ query = f"{query}&{enc_params}"
477
+ else:
478
+ query = enc_params
479
+
480
+ url = requote_uri(urlunparse([scheme, netloc, path, None, query, fragment]))
481
+ self.url = url
482
+
483
+ def prepare_headers(self, headers):
484
+ """Prepares the given HTTP headers."""
485
+
486
+ self.headers = CaseInsensitiveDict()
487
+ if headers:
488
+ for header in headers.items():
489
+ # Raise exception on invalid header value.
490
+ check_header_validity(header)
491
+ name, value = header
492
+ self.headers[to_native_string(name)] = value
493
+
494
+ def prepare_body(self, data, files, json=None):
495
+ """Prepares the given HTTP body data."""
496
+
497
+ # Check if file, fo, generator, iterator.
498
+ # If not, run through normal process.
499
+
500
+ # Nottin' on you.
501
+ body = None
502
+ content_type = None
503
+
504
+ if not data and json is not None:
505
+ # urllib3 requires a bytes-like body. Python 2's json.dumps
506
+ # provides this natively, but Python 3 gives a Unicode string.
507
+ content_type = "application/json"
508
+
509
+ try:
510
+ body = complexjson.dumps(json, allow_nan=False)
511
+ except ValueError as ve:
512
+ raise InvalidJSONError(ve, request=self)
513
+
514
+ if not isinstance(body, bytes):
515
+ body = body.encode("utf-8")
516
+
517
+ is_stream = all(
518
+ [
519
+ hasattr(data, "__iter__"),
520
+ not isinstance(data, (basestring, list, tuple, Mapping)),
521
+ ]
522
+ )
523
+
524
+ if is_stream:
525
+ try:
526
+ length = super_len(data)
527
+ except (TypeError, AttributeError, UnsupportedOperation):
528
+ length = None
529
+
530
+ body = data
531
+
532
+ if getattr(body, "tell", None) is not None:
533
+ # Record the current file position before reading.
534
+ # This will allow us to rewind a file in the event
535
+ # of a redirect.
536
+ try:
537
+ self._body_position = body.tell()
538
+ except OSError:
539
+ # This differentiates from None, allowing us to catch
540
+ # a failed `tell()` later when trying to rewind the body
541
+ self._body_position = object()
542
+
543
+ if files:
544
+ raise NotImplementedError(
545
+ "Streamed bodies and files are mutually exclusive."
546
+ )
547
+
548
+ if length:
549
+ self.headers["Content-Length"] = builtin_str(length)
550
+ else:
551
+ self.headers["Transfer-Encoding"] = "chunked"
552
+ else:
553
+ # Multi-part file uploads.
554
+ if files:
555
+ (body, content_type) = self._encode_files(files, data)
556
+ else:
557
+ if data:
558
+ body = self._encode_params(data)
559
+ if isinstance(data, basestring) or hasattr(data, "read"):
560
+ content_type = None
561
+ else:
562
+ content_type = "application/x-www-form-urlencoded"
563
+
564
+ self.prepare_content_length(body)
565
+
566
+ # Add content-type if it wasn't explicitly provided.
567
+ if content_type and ("content-type" not in self.headers):
568
+ self.headers["Content-Type"] = content_type
569
+
570
+ self.body = body
571
+
572
+ def prepare_content_length(self, body):
573
+ """Prepare Content-Length header based on request method and body"""
574
+ if body is not None:
575
+ length = super_len(body)
576
+ if length:
577
+ # If length exists, set it. Otherwise, we fallback
578
+ # to Transfer-Encoding: chunked.
579
+ self.headers["Content-Length"] = builtin_str(length)
580
+ elif (
581
+ self.method not in ("GET", "HEAD")
582
+ and self.headers.get("Content-Length") is None
583
+ ):
584
+ # Set Content-Length to 0 for methods that can have a body
585
+ # but don't provide one. (i.e. not GET or HEAD)
586
+ self.headers["Content-Length"] = "0"
587
+
588
+ def prepare_auth(self, auth, url=""):
589
+ """Prepares the given HTTP auth data."""
590
+
591
+ # If no Auth is explicitly provided, extract it from the URL first.
592
+ if auth is None:
593
+ url_auth = get_auth_from_url(self.url)
594
+ auth = url_auth if any(url_auth) else None
595
+
596
+ if auth:
597
+ if isinstance(auth, tuple) and len(auth) == 2:
598
+ # special-case basic HTTP auth
599
+ auth = HTTPBasicAuth(*auth)
600
+
601
+ # Allow auth to make its changes.
602
+ r = auth(self)
603
+
604
+ # Update self to reflect the auth changes.
605
+ self.__dict__.update(r.__dict__)
606
+
607
+ # Recompute Content-Length
608
+ self.prepare_content_length(self.body)
609
+
610
+ def prepare_cookies(self, cookies):
611
+ """Prepares the given HTTP cookie data.
612
+
613
+ This function eventually generates a ``Cookie`` header from the
614
+ given cookies using cookielib. Due to cookielib's design, the header
615
+ will not be regenerated if it already exists, meaning this function
616
+ can only be called once for the life of the
617
+ :class:`PreparedRequest <PreparedRequest>` object. Any subsequent calls
618
+ to ``prepare_cookies`` will have no actual effect, unless the "Cookie"
619
+ header is removed beforehand.
620
+ """
621
+ if isinstance(cookies, cookielib.CookieJar):
622
+ self._cookies = cookies
623
+ else:
624
+ self._cookies = cookiejar_from_dict(cookies)
625
+
626
+ cookie_header = get_cookie_header(self._cookies, self)
627
+ if cookie_header is not None:
628
+ self.headers["Cookie"] = cookie_header
629
+
630
+ def prepare_hooks(self, hooks):
631
+ """Prepares the given hooks."""
632
+ # hooks can be passed as None to the prepare method and to this
633
+ # method. To prevent iterating over None, simply use an empty list
634
+ # if hooks is False-y
635
+ hooks = hooks or []
636
+ for event in hooks:
637
+ self.register_hook(event, hooks[event])
638
+
639
+
640
+ class Response:
641
+ """The :class:`Response <Response>` object, which contains a
642
+ server's response to an HTTP request.
643
+ """
644
+
645
+ __attrs__ = [
646
+ "_content",
647
+ "status_code",
648
+ "headers",
649
+ "url",
650
+ "history",
651
+ "encoding",
652
+ "reason",
653
+ "cookies",
654
+ "elapsed",
655
+ "request",
656
+ ]
657
+
658
+ def __init__(self):
659
+ self._content = False
660
+ self._content_consumed = False
661
+ self._next = None
662
+
663
+ #: Integer Code of responded HTTP Status, e.g. 404 or 200.
664
+ self.status_code = None
665
+
666
+ #: Case-insensitive Dictionary of Response Headers.
667
+ #: For example, ``headers['content-encoding']`` will return the
668
+ #: value of a ``'Content-Encoding'`` response header.
669
+ self.headers = CaseInsensitiveDict()
670
+
671
+ #: File-like object representation of response (for advanced usage).
672
+ #: Use of ``raw`` requires that ``stream=True`` be set on the request.
673
+ #: This requirement does not apply for use internally to Requests.
674
+ self.raw = None
675
+
676
+ #: Final URL location of Response.
677
+ self.url = None
678
+
679
+ #: Encoding to decode with when accessing r.text.
680
+ self.encoding = None
681
+
682
+ #: A list of :class:`Response <Response>` objects from
683
+ #: the history of the Request. Any redirect responses will end
684
+ #: up here. The list is sorted from the oldest to the most recent request.
685
+ self.history = []
686
+
687
+ #: Textual reason of responded HTTP Status, e.g. "Not Found" or "OK".
688
+ self.reason = None
689
+
690
+ #: A CookieJar of Cookies the server sent back.
691
+ self.cookies = cookiejar_from_dict({})
692
+
693
+ #: The amount of time elapsed between sending the request
694
+ #: and the arrival of the response (as a timedelta).
695
+ #: This property specifically measures the time taken between sending
696
+ #: the first byte of the request and finishing parsing the headers. It
697
+ #: is therefore unaffected by consuming the response content or the
698
+ #: value of the ``stream`` keyword argument.
699
+ self.elapsed = datetime.timedelta(0)
700
+
701
+ #: The :class:`PreparedRequest <PreparedRequest>` object to which this
702
+ #: is a response.
703
+ self.request = None
704
+
705
+ def __enter__(self):
706
+ return self
707
+
708
+ def __exit__(self, *args):
709
+ self.close()
710
+
711
+ def __getstate__(self):
712
+ # Consume everything; accessing the content attribute makes
713
+ # sure the content has been fully read.
714
+ if not self._content_consumed:
715
+ self.content
716
+
717
+ return {attr: getattr(self, attr, None) for attr in self.__attrs__}
718
+
719
+ def __setstate__(self, state):
720
+ for name, value in state.items():
721
+ setattr(self, name, value)
722
+
723
+ # pickled objects do not have .raw
724
+ setattr(self, "_content_consumed", True)
725
+ setattr(self, "raw", None)
726
+
727
+ def __repr__(self):
728
+ return f"<Response [{self.status_code}]>"
729
+
730
+ def __bool__(self):
731
+ """Returns True if :attr:`status_code` is less than 400.
732
+
733
+ This attribute checks if the status code of the response is between
734
+ 400 and 600 to see if there was a client error or a server error. If
735
+ the status code, is between 200 and 400, this will return True. This
736
+ is **not** a check to see if the response code is ``200 OK``.
737
+ """
738
+ return self.ok
739
+
740
+ def __nonzero__(self):
741
+ """Returns True if :attr:`status_code` is less than 400.
742
+
743
+ This attribute checks if the status code of the response is between
744
+ 400 and 600 to see if there was a client error or a server error. If
745
+ the status code, is between 200 and 400, this will return True. This
746
+ is **not** a check to see if the response code is ``200 OK``.
747
+ """
748
+ return self.ok
749
+
750
+ def __iter__(self):
751
+ """Allows you to use a response as an iterator."""
752
+ return self.iter_content(128)
753
+
754
+ @property
755
+ def ok(self):
756
+ """Returns True if :attr:`status_code` is less than 400, False if not.
757
+
758
+ This attribute checks if the status code of the response is between
759
+ 400 and 600 to see if there was a client error or a server error. If
760
+ the status code is between 200 and 400, this will return True. This
761
+ is **not** a check to see if the response code is ``200 OK``.
762
+ """
763
+ try:
764
+ self.raise_for_status()
765
+ except HTTPError:
766
+ return False
767
+ return True
768
+
769
+ @property
770
+ def is_redirect(self):
771
+ """True if this Response is a well-formed HTTP redirect that could have
772
+ been processed automatically (by :meth:`Session.resolve_redirects`).
773
+ """
774
+ return "location" in self.headers and self.status_code in REDIRECT_STATI
775
+
776
+ @property
777
+ def is_permanent_redirect(self):
778
+ """True if this Response one of the permanent versions of redirect."""
779
+ return "location" in self.headers and self.status_code in (
780
+ codes.moved_permanently,
781
+ codes.permanent_redirect,
782
+ )
783
+
784
+ @property
785
+ def next(self):
786
+ """Returns a PreparedRequest for the next request in a redirect chain, if there is one."""
787
+ return self._next
788
+
789
+ @property
790
+ def apparent_encoding(self):
791
+ """The apparent encoding, provided by the charset_normalizer or chardet libraries."""
792
+ if chardet is not None:
793
+ return chardet.detect(self.content)["encoding"]
794
+ else:
795
+ # If no character detection library is available, we'll fall back
796
+ # to a standard Python utf-8 str.
797
+ return "utf-8"
798
+
799
+ def iter_content(self, chunk_size=1, decode_unicode=False):
800
+ """Iterates over the response data. When stream=True is set on the
801
+ request, this avoids reading the content at once into memory for
802
+ large responses. The chunk size is the number of bytes it should
803
+ read into memory. This is not necessarily the length of each item
804
+ returned as decoding can take place.
805
+
806
+ chunk_size must be of type int or None. A value of None will
807
+ function differently depending on the value of `stream`.
808
+ stream=True will read data as it arrives in whatever size the
809
+ chunks are received. If stream=False, data is returned as
810
+ a single chunk.
811
+
812
+ If decode_unicode is True, content will be decoded using the best
813
+ available encoding based on the response.
814
+ """
815
+
816
+ def generate():
817
+ # Special case for urllib3.
818
+ if hasattr(self.raw, "stream"):
819
+ try:
820
+ yield from self.raw.stream(chunk_size, decode_content=True)
821
+ except ProtocolError as e:
822
+ raise ChunkedEncodingError(e)
823
+ except DecodeError as e:
824
+ raise ContentDecodingError(e)
825
+ except ReadTimeoutError as e:
826
+ raise ConnectionError(e)
827
+ except SSLError as e:
828
+ raise RequestsSSLError(e)
829
+ else:
830
+ # Standard file-like object.
831
+ while True:
832
+ chunk = self.raw.read(chunk_size)
833
+ if not chunk:
834
+ break
835
+ yield chunk
836
+
837
+ self._content_consumed = True
838
+
839
+ if self._content_consumed and isinstance(self._content, bool):
840
+ raise StreamConsumedError()
841
+ elif chunk_size is not None and not isinstance(chunk_size, int):
842
+ raise TypeError(
843
+ f"chunk_size must be an int, it is instead a {type(chunk_size)}."
844
+ )
845
+ # simulate reading small chunks of the content
846
+ reused_chunks = iter_slices(self._content, chunk_size)
847
+
848
+ stream_chunks = generate()
849
+
850
+ chunks = reused_chunks if self._content_consumed else stream_chunks
851
+
852
+ if decode_unicode:
853
+ chunks = stream_decode_response_unicode(chunks, self)
854
+
855
+ return chunks
856
+
857
+ def iter_lines(
858
+ self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=False, delimiter=None
859
+ ):
860
+ """Iterates over the response data, one line at a time. When
861
+ stream=True is set on the request, this avoids reading the
862
+ content at once into memory for large responses.
863
+
864
+ .. note:: This method is not reentrant safe.
865
+ """
866
+
867
+ pending = None
868
+
869
+ for chunk in self.iter_content(
870
+ chunk_size=chunk_size, decode_unicode=decode_unicode
871
+ ):
872
+ if pending is not None:
873
+ chunk = pending + chunk
874
+
875
+ if delimiter:
876
+ lines = chunk.split(delimiter)
877
+ else:
878
+ lines = chunk.splitlines()
879
+
880
+ if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:
881
+ pending = lines.pop()
882
+ else:
883
+ pending = None
884
+
885
+ yield from lines
886
+
887
+ if pending is not None:
888
+ yield pending
889
+
890
+ @property
891
+ def content(self):
892
+ """Content of the response, in bytes."""
893
+
894
+ if self._content is False:
895
+ # Read the contents.
896
+ if self._content_consumed:
897
+ raise RuntimeError("The content for this response was already consumed")
898
+
899
+ if self.status_code == 0 or self.raw is None:
900
+ self._content = None
901
+ else:
902
+ self._content = b"".join(self.iter_content(CONTENT_CHUNK_SIZE)) or b""
903
+
904
+ self._content_consumed = True
905
+ # don't need to release the connection; that's been handled by urllib3
906
+ # since we exhausted the data.
907
+ return self._content
908
+
909
+ @property
910
+ def text(self):
911
+ """Content of the response, in unicode.
912
+
913
+ If Response.encoding is None, encoding will be guessed using
914
+ ``charset_normalizer`` or ``chardet``.
915
+
916
+ The encoding of the response content is determined based solely on HTTP
917
+ headers, following RFC 2616 to the letter. If you can take advantage of
918
+ non-HTTP knowledge to make a better guess at the encoding, you should
919
+ set ``r.encoding`` appropriately before accessing this property.
920
+ """
921
+
922
+ # Try charset from content-type
923
+ content = None
924
+ encoding = self.encoding
925
+
926
+ if not self.content:
927
+ return ""
928
+
929
+ # Fallback to auto-detected encoding.
930
+ if self.encoding is None:
931
+ encoding = self.apparent_encoding
932
+
933
+ # Decode unicode from given encoding.
934
+ try:
935
+ content = str(self.content, encoding, errors="replace")
936
+ except (LookupError, TypeError):
937
+ # A LookupError is raised if the encoding was not found which could
938
+ # indicate a misspelling or similar mistake.
939
+ #
940
+ # A TypeError can be raised if encoding is None
941
+ #
942
+ # So we try blindly encoding.
943
+ content = str(self.content, errors="replace")
944
+
945
+ return content
946
+
947
+ def json(self, **kwargs):
948
+ r"""Returns the json-encoded content of a response, if any.
949
+
950
+ :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
951
+ :raises requests.exceptions.JSONDecodeError: If the response body does not
952
+ contain valid json.
953
+ """
954
+
955
+ if not self.encoding and self.content and len(self.content) > 3:
956
+ # No encoding set. JSON RFC 4627 section 3 states we should expect
957
+ # UTF-8, -16 or -32. Detect which one to use; If the detection or
958
+ # decoding fails, fall back to `self.text` (using charset_normalizer to make
959
+ # a best guess).
960
+ encoding = guess_json_utf(self.content)
961
+ if encoding is not None:
962
+ try:
963
+ return complexjson.loads(self.content.decode(encoding), **kwargs)
964
+ except UnicodeDecodeError:
965
+ # Wrong UTF codec detected; usually because it's not UTF-8
966
+ # but some other 8-bit codec. This is an RFC violation,
967
+ # and the server didn't bother to tell us what codec *was*
968
+ # used.
969
+ pass
970
+ except JSONDecodeError as e:
971
+ raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
972
+
973
+ try:
974
+ return complexjson.loads(self.text, **kwargs)
975
+ except JSONDecodeError as e:
976
+ # Catch JSON-related errors and raise as requests.JSONDecodeError
977
+ # This aliases json.JSONDecodeError and simplejson.JSONDecodeError
978
+ raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
979
+
980
+ @property
981
+ def links(self):
982
+ """Returns the parsed header links of the response, if any."""
983
+
984
+ header = self.headers.get("link")
985
+
986
+ resolved_links = {}
987
+
988
+ if header:
989
+ links = parse_header_links(header)
990
+
991
+ for link in links:
992
+ key = link.get("rel") or link.get("url")
993
+ resolved_links[key] = link
994
+
995
+ return resolved_links
996
+
997
+ def raise_for_status(self):
998
+ """Raises :class:`HTTPError`, if one occurred."""
999
+
1000
+ http_error_msg = ""
1001
+ if isinstance(self.reason, bytes):
1002
+ # We attempt to decode utf-8 first because some servers
1003
+ # choose to localize their reason strings. If the string
1004
+ # isn't utf-8, we fall back to iso-8859-1 for all other
1005
+ # encodings. (See PR #3538)
1006
+ try:
1007
+ reason = self.reason.decode("utf-8")
1008
+ except UnicodeDecodeError:
1009
+ reason = self.reason.decode("iso-8859-1")
1010
+ else:
1011
+ reason = self.reason
1012
+
1013
+ if 400 <= self.status_code < 500:
1014
+ http_error_msg = (
1015
+ f"{self.status_code} Client Error: {reason} for url: {self.url}"
1016
+ )
1017
+
1018
+ elif 500 <= self.status_code < 600:
1019
+ http_error_msg = (
1020
+ f"{self.status_code} Server Error: {reason} for url: {self.url}"
1021
+ )
1022
+
1023
+ if http_error_msg:
1024
+ raise HTTPError(http_error_msg, response=self)
1025
+
1026
+ def close(self):
1027
+ """Releases the connection back to the pool. Once this method has been
1028
+ called the underlying ``raw`` object must not be accessed again.
1029
+
1030
+ *Note: Should not normally need to be called explicitly.*
1031
+ """
1032
+ if not self._content_consumed:
1033
+ self.raw.close()
1034
+
1035
+ release_conn = getattr(self.raw, "release_conn", None)
1036
+ if release_conn is not None:
1037
+ release_conn()
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/sessions.py ADDED
@@ -0,0 +1,831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.sessions
3
+ ~~~~~~~~~~~~~~~~~
4
+
5
+ This module provides a Session object to manage and persist settings across
6
+ requests (cookies, auth, proxies).
7
+ """
8
+ import os
9
+ import sys
10
+ import time
11
+ from collections import OrderedDict
12
+ from datetime import timedelta
13
+
14
+ from ._internal_utils import to_native_string
15
+ from .adapters import HTTPAdapter
16
+ from .auth import _basic_auth_str
17
+ from .compat import Mapping, cookielib, urljoin, urlparse
18
+ from .cookies import (
19
+ RequestsCookieJar,
20
+ cookiejar_from_dict,
21
+ extract_cookies_to_jar,
22
+ merge_cookies,
23
+ )
24
+ from .exceptions import (
25
+ ChunkedEncodingError,
26
+ ContentDecodingError,
27
+ InvalidSchema,
28
+ TooManyRedirects,
29
+ )
30
+ from .hooks import default_hooks, dispatch_hook
31
+
32
+ # formerly defined here, reexposed here for backward compatibility
33
+ from .models import ( # noqa: F401
34
+ DEFAULT_REDIRECT_LIMIT,
35
+ REDIRECT_STATI,
36
+ PreparedRequest,
37
+ Request,
38
+ )
39
+ from .status_codes import codes
40
+ from .structures import CaseInsensitiveDict
41
+ from .utils import ( # noqa: F401
42
+ DEFAULT_PORTS,
43
+ default_headers,
44
+ get_auth_from_url,
45
+ get_environ_proxies,
46
+ get_netrc_auth,
47
+ requote_uri,
48
+ resolve_proxies,
49
+ rewind_body,
50
+ should_bypass_proxies,
51
+ to_key_val_list,
52
+ )
53
+
54
+ # Preferred clock, based on which one is more accurate on a given system.
55
+ if sys.platform == "win32":
56
+ preferred_clock = time.perf_counter
57
+ else:
58
+ preferred_clock = time.time
59
+
60
+
61
+ def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
62
+ """Determines appropriate setting for a given request, taking into account
63
+ the explicit setting on that request, and the setting in the session. If a
64
+ setting is a dictionary, they will be merged together using `dict_class`
65
+ """
66
+
67
+ if session_setting is None:
68
+ return request_setting
69
+
70
+ if request_setting is None:
71
+ return session_setting
72
+
73
+ # Bypass if not a dictionary (e.g. verify)
74
+ if not (
75
+ isinstance(session_setting, Mapping) and isinstance(request_setting, Mapping)
76
+ ):
77
+ return request_setting
78
+
79
+ merged_setting = dict_class(to_key_val_list(session_setting))
80
+ merged_setting.update(to_key_val_list(request_setting))
81
+
82
+ # Remove keys that are set to None. Extract keys first to avoid altering
83
+ # the dictionary during iteration.
84
+ none_keys = [k for (k, v) in merged_setting.items() if v is None]
85
+ for key in none_keys:
86
+ del merged_setting[key]
87
+
88
+ return merged_setting
89
+
90
+
91
+ def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):
92
+ """Properly merges both requests and session hooks.
93
+
94
+ This is necessary because when request_hooks == {'response': []}, the
95
+ merge breaks Session hooks entirely.
96
+ """
97
+ if session_hooks is None or session_hooks.get("response") == []:
98
+ return request_hooks
99
+
100
+ if request_hooks is None or request_hooks.get("response") == []:
101
+ return session_hooks
102
+
103
+ return merge_setting(request_hooks, session_hooks, dict_class)
104
+
105
+
106
+ class SessionRedirectMixin:
107
+ def get_redirect_target(self, resp):
108
+ """Receives a Response. Returns a redirect URI or ``None``"""
109
+ # Due to the nature of how requests processes redirects this method will
110
+ # be called at least once upon the original response and at least twice
111
+ # on each subsequent redirect response (if any).
112
+ # If a custom mixin is used to handle this logic, it may be advantageous
113
+ # to cache the redirect location onto the response object as a private
114
+ # attribute.
115
+ if resp.is_redirect:
116
+ location = resp.headers["location"]
117
+ # Currently the underlying http module on py3 decode headers
118
+ # in latin1, but empirical evidence suggests that latin1 is very
119
+ # rarely used with non-ASCII characters in HTTP headers.
120
+ # It is more likely to get UTF8 header rather than latin1.
121
+ # This causes incorrect handling of UTF8 encoded location headers.
122
+ # To solve this, we re-encode the location in latin1.
123
+ location = location.encode("latin1")
124
+ return to_native_string(location, "utf8")
125
+ return None
126
+
127
+ def should_strip_auth(self, old_url, new_url):
128
+ """Decide whether Authorization header should be removed when redirecting"""
129
+ old_parsed = urlparse(old_url)
130
+ new_parsed = urlparse(new_url)
131
+ if old_parsed.hostname != new_parsed.hostname:
132
+ return True
133
+ # Special case: allow http -> https redirect when using the standard
134
+ # ports. This isn't specified by RFC 7235, but is kept to avoid
135
+ # breaking backwards compatibility with older versions of requests
136
+ # that allowed any redirects on the same host.
137
+ if (
138
+ old_parsed.scheme == "http"
139
+ and old_parsed.port in (80, None)
140
+ and new_parsed.scheme == "https"
141
+ and new_parsed.port in (443, None)
142
+ ):
143
+ return False
144
+
145
+ # Handle default port usage corresponding to scheme.
146
+ changed_port = old_parsed.port != new_parsed.port
147
+ changed_scheme = old_parsed.scheme != new_parsed.scheme
148
+ default_port = (DEFAULT_PORTS.get(old_parsed.scheme, None), None)
149
+ if (
150
+ not changed_scheme
151
+ and old_parsed.port in default_port
152
+ and new_parsed.port in default_port
153
+ ):
154
+ return False
155
+
156
+ # Standard case: root URI must match
157
+ return changed_port or changed_scheme
158
+
159
+ def resolve_redirects(
160
+ self,
161
+ resp,
162
+ req,
163
+ stream=False,
164
+ timeout=None,
165
+ verify=True,
166
+ cert=None,
167
+ proxies=None,
168
+ yield_requests=False,
169
+ **adapter_kwargs,
170
+ ):
171
+ """Receives a Response. Returns a generator of Responses or Requests."""
172
+
173
+ hist = [] # keep track of history
174
+
175
+ url = self.get_redirect_target(resp)
176
+ previous_fragment = urlparse(req.url).fragment
177
+ while url:
178
+ prepared_request = req.copy()
179
+
180
+ # Update history and keep track of redirects.
181
+ # resp.history must ignore the original request in this loop
182
+ hist.append(resp)
183
+ resp.history = hist[1:]
184
+
185
+ try:
186
+ resp.content # Consume socket so it can be released
187
+ except (ChunkedEncodingError, ContentDecodingError, RuntimeError):
188
+ resp.raw.read(decode_content=False)
189
+
190
+ if len(resp.history) >= self.max_redirects:
191
+ raise TooManyRedirects(
192
+ f"Exceeded {self.max_redirects} redirects.", response=resp
193
+ )
194
+
195
+ # Release the connection back into the pool.
196
+ resp.close()
197
+
198
+ # Handle redirection without scheme (see: RFC 1808 Section 4)
199
+ if url.startswith("//"):
200
+ parsed_rurl = urlparse(resp.url)
201
+ url = ":".join([to_native_string(parsed_rurl.scheme), url])
202
+
203
+ # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)
204
+ parsed = urlparse(url)
205
+ if parsed.fragment == "" and previous_fragment:
206
+ parsed = parsed._replace(fragment=previous_fragment)
207
+ elif parsed.fragment:
208
+ previous_fragment = parsed.fragment
209
+ url = parsed.geturl()
210
+
211
+ # Facilitate relative 'location' headers, as allowed by RFC 7231.
212
+ # (e.g. '/path/to/resource' instead of 'http://domain.tld/path/to/resource')
213
+ # Compliant with RFC3986, we percent encode the url.
214
+ if not parsed.netloc:
215
+ url = urljoin(resp.url, requote_uri(url))
216
+ else:
217
+ url = requote_uri(url)
218
+
219
+ prepared_request.url = to_native_string(url)
220
+
221
+ self.rebuild_method(prepared_request, resp)
222
+
223
+ # https://github.com/psf/requests/issues/1084
224
+ if resp.status_code not in (
225
+ codes.temporary_redirect,
226
+ codes.permanent_redirect,
227
+ ):
228
+ # https://github.com/psf/requests/issues/3490
229
+ purged_headers = ("Content-Length", "Content-Type", "Transfer-Encoding")
230
+ for header in purged_headers:
231
+ prepared_request.headers.pop(header, None)
232
+ prepared_request.body = None
233
+
234
+ headers = prepared_request.headers
235
+ headers.pop("Cookie", None)
236
+
237
+ # Extract any cookies sent on the response to the cookiejar
238
+ # in the new request. Because we've mutated our copied prepared
239
+ # request, use the old one that we haven't yet touched.
240
+ extract_cookies_to_jar(prepared_request._cookies, req, resp.raw)
241
+ merge_cookies(prepared_request._cookies, self.cookies)
242
+ prepared_request.prepare_cookies(prepared_request._cookies)
243
+
244
+ # Rebuild auth and proxy information.
245
+ proxies = self.rebuild_proxies(prepared_request, proxies)
246
+ self.rebuild_auth(prepared_request, resp)
247
+
248
+ # A failed tell() sets `_body_position` to `object()`. This non-None
249
+ # value ensures `rewindable` will be True, allowing us to raise an
250
+ # UnrewindableBodyError, instead of hanging the connection.
251
+ rewindable = prepared_request._body_position is not None and (
252
+ "Content-Length" in headers or "Transfer-Encoding" in headers
253
+ )
254
+
255
+ # Attempt to rewind consumed file-like object.
256
+ if rewindable:
257
+ rewind_body(prepared_request)
258
+
259
+ # Override the original request.
260
+ req = prepared_request
261
+
262
+ if yield_requests:
263
+ yield req
264
+ else:
265
+ resp = self.send(
266
+ req,
267
+ stream=stream,
268
+ timeout=timeout,
269
+ verify=verify,
270
+ cert=cert,
271
+ proxies=proxies,
272
+ allow_redirects=False,
273
+ **adapter_kwargs,
274
+ )
275
+
276
+ extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)
277
+
278
+ # extract redirect url, if any, for the next loop
279
+ url = self.get_redirect_target(resp)
280
+ yield resp
281
+
282
+ def rebuild_auth(self, prepared_request, response):
283
+ """When being redirected we may want to strip authentication from the
284
+ request to avoid leaking credentials. This method intelligently removes
285
+ and reapplies authentication where possible to avoid credential loss.
286
+ """
287
+ headers = prepared_request.headers
288
+ url = prepared_request.url
289
+
290
+ if "Authorization" in headers and self.should_strip_auth(
291
+ response.request.url, url
292
+ ):
293
+ # If we get redirected to a new host, we should strip out any
294
+ # authentication headers.
295
+ del headers["Authorization"]
296
+
297
+ # .netrc might have more auth for us on our new host.
298
+ new_auth = get_netrc_auth(url) if self.trust_env else None
299
+ if new_auth is not None:
300
+ prepared_request.prepare_auth(new_auth)
301
+
302
+ def rebuild_proxies(self, prepared_request, proxies):
303
+ """This method re-evaluates the proxy configuration by considering the
304
+ environment variables. If we are redirected to a URL covered by
305
+ NO_PROXY, we strip the proxy configuration. Otherwise, we set missing
306
+ proxy keys for this URL (in case they were stripped by a previous
307
+ redirect).
308
+
309
+ This method also replaces the Proxy-Authorization header where
310
+ necessary.
311
+
312
+ :rtype: dict
313
+ """
314
+ headers = prepared_request.headers
315
+ scheme = urlparse(prepared_request.url).scheme
316
+ new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)
317
+
318
+ if "Proxy-Authorization" in headers:
319
+ del headers["Proxy-Authorization"]
320
+
321
+ try:
322
+ username, password = get_auth_from_url(new_proxies[scheme])
323
+ except KeyError:
324
+ username, password = None, None
325
+
326
+ # urllib3 handles proxy authorization for us in the standard adapter.
327
+ # Avoid appending this to TLS tunneled requests where it may be leaked.
328
+ if not scheme.startswith("https") and username and password:
329
+ headers["Proxy-Authorization"] = _basic_auth_str(username, password)
330
+
331
+ return new_proxies
332
+
333
+ def rebuild_method(self, prepared_request, response):
334
+ """When being redirected we may want to change the method of the request
335
+ based on certain specs or browser behavior.
336
+ """
337
+ method = prepared_request.method
338
+
339
+ # https://tools.ietf.org/html/rfc7231#section-6.4.4
340
+ if response.status_code == codes.see_other and method != "HEAD":
341
+ method = "GET"
342
+
343
+ # Do what the browsers do, despite standards...
344
+ # First, turn 302s into GETs.
345
+ if response.status_code == codes.found and method != "HEAD":
346
+ method = "GET"
347
+
348
+ # Second, if a POST is responded to with a 301, turn it into a GET.
349
+ # This bizarre behaviour is explained in Issue 1704.
350
+ if response.status_code == codes.moved and method == "POST":
351
+ method = "GET"
352
+
353
+ prepared_request.method = method
354
+
355
+
356
+ class Session(SessionRedirectMixin):
357
+ """A Requests session.
358
+
359
+ Provides cookie persistence, connection-pooling, and configuration.
360
+
361
+ Basic Usage::
362
+
363
+ >>> import requests
364
+ >>> s = requests.Session()
365
+ >>> s.get('https://httpbin.org/get')
366
+ <Response [200]>
367
+
368
+ Or as a context manager::
369
+
370
+ >>> with requests.Session() as s:
371
+ ... s.get('https://httpbin.org/get')
372
+ <Response [200]>
373
+ """
374
+
375
+ __attrs__ = [
376
+ "headers",
377
+ "cookies",
378
+ "auth",
379
+ "proxies",
380
+ "hooks",
381
+ "params",
382
+ "verify",
383
+ "cert",
384
+ "adapters",
385
+ "stream",
386
+ "trust_env",
387
+ "max_redirects",
388
+ ]
389
+
390
+ def __init__(self):
391
+ #: A case-insensitive dictionary of headers to be sent on each
392
+ #: :class:`Request <Request>` sent from this
393
+ #: :class:`Session <Session>`.
394
+ self.headers = default_headers()
395
+
396
+ #: Default Authentication tuple or object to attach to
397
+ #: :class:`Request <Request>`.
398
+ self.auth = None
399
+
400
+ #: Dictionary mapping protocol or protocol and host to the URL of the proxy
401
+ #: (e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'}) to
402
+ #: be used on each :class:`Request <Request>`.
403
+ self.proxies = {}
404
+
405
+ #: Event-handling hooks.
406
+ self.hooks = default_hooks()
407
+
408
+ #: Dictionary of querystring data to attach to each
409
+ #: :class:`Request <Request>`. The dictionary values may be lists for
410
+ #: representing multivalued query parameters.
411
+ self.params = {}
412
+
413
+ #: Stream response content default.
414
+ self.stream = False
415
+
416
+ #: SSL Verification default.
417
+ #: Defaults to `True`, requiring requests to verify the TLS certificate at the
418
+ #: remote end.
419
+ #: If verify is set to `False`, requests will accept any TLS certificate
420
+ #: presented by the server, and will ignore hostname mismatches and/or
421
+ #: expired certificates, which will make your application vulnerable to
422
+ #: man-in-the-middle (MitM) attacks.
423
+ #: Only set this to `False` for testing.
424
+ self.verify = True
425
+
426
+ #: SSL client certificate default, if String, path to ssl client
427
+ #: cert file (.pem). If Tuple, ('cert', 'key') pair.
428
+ self.cert = None
429
+
430
+ #: Maximum number of redirects allowed. If the request exceeds this
431
+ #: limit, a :class:`TooManyRedirects` exception is raised.
432
+ #: This defaults to requests.models.DEFAULT_REDIRECT_LIMIT, which is
433
+ #: 30.
434
+ self.max_redirects = DEFAULT_REDIRECT_LIMIT
435
+
436
+ #: Trust environment settings for proxy configuration, default
437
+ #: authentication and similar.
438
+ self.trust_env = True
439
+
440
+ #: A CookieJar containing all currently outstanding cookies set on this
441
+ #: session. By default it is a
442
+ #: :class:`RequestsCookieJar <requests.cookies.RequestsCookieJar>`, but
443
+ #: may be any other ``cookielib.CookieJar`` compatible object.
444
+ self.cookies = cookiejar_from_dict({})
445
+
446
+ # Default connection adapters.
447
+ self.adapters = OrderedDict()
448
+ self.mount("https://", HTTPAdapter())
449
+ self.mount("http://", HTTPAdapter())
450
+
451
+ def __enter__(self):
452
+ return self
453
+
454
+ def __exit__(self, *args):
455
+ self.close()
456
+
457
+ def prepare_request(self, request):
458
+ """Constructs a :class:`PreparedRequest <PreparedRequest>` for
459
+ transmission and returns it. The :class:`PreparedRequest` has settings
460
+ merged from the :class:`Request <Request>` instance and those of the
461
+ :class:`Session`.
462
+
463
+ :param request: :class:`Request` instance to prepare with this
464
+ session's settings.
465
+ :rtype: requests.PreparedRequest
466
+ """
467
+ cookies = request.cookies or {}
468
+
469
+ # Bootstrap CookieJar.
470
+ if not isinstance(cookies, cookielib.CookieJar):
471
+ cookies = cookiejar_from_dict(cookies)
472
+
473
+ # Merge with session cookies
474
+ merged_cookies = merge_cookies(
475
+ merge_cookies(RequestsCookieJar(), self.cookies), cookies
476
+ )
477
+
478
+ # Set environment's basic authentication if not explicitly set.
479
+ auth = request.auth
480
+ if self.trust_env and not auth and not self.auth:
481
+ auth = get_netrc_auth(request.url)
482
+
483
+ p = PreparedRequest()
484
+ p.prepare(
485
+ method=request.method.upper(),
486
+ url=request.url,
487
+ files=request.files,
488
+ data=request.data,
489
+ json=request.json,
490
+ headers=merge_setting(
491
+ request.headers, self.headers, dict_class=CaseInsensitiveDict
492
+ ),
493
+ params=merge_setting(request.params, self.params),
494
+ auth=merge_setting(auth, self.auth),
495
+ cookies=merged_cookies,
496
+ hooks=merge_hooks(request.hooks, self.hooks),
497
+ )
498
+ return p
499
+
500
+ def request(
501
+ self,
502
+ method,
503
+ url,
504
+ params=None,
505
+ data=None,
506
+ headers=None,
507
+ cookies=None,
508
+ files=None,
509
+ auth=None,
510
+ timeout=None,
511
+ allow_redirects=True,
512
+ proxies=None,
513
+ hooks=None,
514
+ stream=None,
515
+ verify=None,
516
+ cert=None,
517
+ json=None,
518
+ ):
519
+ """Constructs a :class:`Request <Request>`, prepares it and sends it.
520
+ Returns :class:`Response <Response>` object.
521
+
522
+ :param method: method for the new :class:`Request` object.
523
+ :param url: URL for the new :class:`Request` object.
524
+ :param params: (optional) Dictionary or bytes to be sent in the query
525
+ string for the :class:`Request`.
526
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
527
+ object to send in the body of the :class:`Request`.
528
+ :param json: (optional) json to send in the body of the
529
+ :class:`Request`.
530
+ :param headers: (optional) Dictionary of HTTP Headers to send with the
531
+ :class:`Request`.
532
+ :param cookies: (optional) Dict or CookieJar object to send with the
533
+ :class:`Request`.
534
+ :param files: (optional) Dictionary of ``'filename': file-like-objects``
535
+ for multipart encoding upload.
536
+ :param auth: (optional) Auth tuple or callable to enable
537
+ Basic/Digest/Custom HTTP Auth.
538
+ :param timeout: (optional) How long to wait for the server to send
539
+ data before giving up, as a float, or a :ref:`(connect timeout,
540
+ read timeout) <timeouts>` tuple.
541
+ :type timeout: float or tuple
542
+ :param allow_redirects: (optional) Set to True by default.
543
+ :type allow_redirects: bool
544
+ :param proxies: (optional) Dictionary mapping protocol or protocol and
545
+ hostname to the URL of the proxy.
546
+ :param hooks: (optional) Dictionary mapping hook name to one event or
547
+ list of events, event must be callable.
548
+ :param stream: (optional) whether to immediately download the response
549
+ content. Defaults to ``False``.
550
+ :param verify: (optional) Either a boolean, in which case it controls whether we verify
551
+ the server's TLS certificate, or a string, in which case it must be a path
552
+ to a CA bundle to use. Defaults to ``True``. When set to
553
+ ``False``, requests will accept any TLS certificate presented by
554
+ the server, and will ignore hostname mismatches and/or expired
555
+ certificates, which will make your application vulnerable to
556
+ man-in-the-middle (MitM) attacks. Setting verify to ``False``
557
+ may be useful during local development or testing.
558
+ :param cert: (optional) if String, path to ssl client cert file (.pem).
559
+ If Tuple, ('cert', 'key') pair.
560
+ :rtype: requests.Response
561
+ """
562
+ # Create the Request.
563
+ req = Request(
564
+ method=method.upper(),
565
+ url=url,
566
+ headers=headers,
567
+ files=files,
568
+ data=data or {},
569
+ json=json,
570
+ params=params or {},
571
+ auth=auth,
572
+ cookies=cookies,
573
+ hooks=hooks,
574
+ )
575
+ prep = self.prepare_request(req)
576
+
577
+ proxies = proxies or {}
578
+
579
+ settings = self.merge_environment_settings(
580
+ prep.url, proxies, stream, verify, cert
581
+ )
582
+
583
+ # Send the request.
584
+ send_kwargs = {
585
+ "timeout": timeout,
586
+ "allow_redirects": allow_redirects,
587
+ }
588
+ send_kwargs.update(settings)
589
+ resp = self.send(prep, **send_kwargs)
590
+
591
+ return resp
592
+
593
+ def get(self, url, **kwargs):
594
+ r"""Sends a GET request. Returns :class:`Response` object.
595
+
596
+ :param url: URL for the new :class:`Request` object.
597
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
598
+ :rtype: requests.Response
599
+ """
600
+
601
+ kwargs.setdefault("allow_redirects", True)
602
+ return self.request("GET", url, **kwargs)
603
+
604
+ def options(self, url, **kwargs):
605
+ r"""Sends a OPTIONS request. Returns :class:`Response` object.
606
+
607
+ :param url: URL for the new :class:`Request` object.
608
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
609
+ :rtype: requests.Response
610
+ """
611
+
612
+ kwargs.setdefault("allow_redirects", True)
613
+ return self.request("OPTIONS", url, **kwargs)
614
+
615
+ def head(self, url, **kwargs):
616
+ r"""Sends a HEAD request. Returns :class:`Response` object.
617
+
618
+ :param url: URL for the new :class:`Request` object.
619
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
620
+ :rtype: requests.Response
621
+ """
622
+
623
+ kwargs.setdefault("allow_redirects", False)
624
+ return self.request("HEAD", url, **kwargs)
625
+
626
+ def post(self, url, data=None, json=None, **kwargs):
627
+ r"""Sends a POST request. Returns :class:`Response` object.
628
+
629
+ :param url: URL for the new :class:`Request` object.
630
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
631
+ object to send in the body of the :class:`Request`.
632
+ :param json: (optional) json to send in the body of the :class:`Request`.
633
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
634
+ :rtype: requests.Response
635
+ """
636
+
637
+ return self.request("POST", url, data=data, json=json, **kwargs)
638
+
639
+ def put(self, url, data=None, **kwargs):
640
+ r"""Sends a PUT request. Returns :class:`Response` object.
641
+
642
+ :param url: URL for the new :class:`Request` object.
643
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
644
+ object to send in the body of the :class:`Request`.
645
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
646
+ :rtype: requests.Response
647
+ """
648
+
649
+ return self.request("PUT", url, data=data, **kwargs)
650
+
651
+ def patch(self, url, data=None, **kwargs):
652
+ r"""Sends a PATCH request. Returns :class:`Response` object.
653
+
654
+ :param url: URL for the new :class:`Request` object.
655
+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like
656
+ object to send in the body of the :class:`Request`.
657
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
658
+ :rtype: requests.Response
659
+ """
660
+
661
+ return self.request("PATCH", url, data=data, **kwargs)
662
+
663
+ def delete(self, url, **kwargs):
664
+ r"""Sends a DELETE request. Returns :class:`Response` object.
665
+
666
+ :param url: URL for the new :class:`Request` object.
667
+ :param \*\*kwargs: Optional arguments that ``request`` takes.
668
+ :rtype: requests.Response
669
+ """
670
+
671
+ return self.request("DELETE", url, **kwargs)
672
+
673
+ def send(self, request, **kwargs):
674
+ """Send a given PreparedRequest.
675
+
676
+ :rtype: requests.Response
677
+ """
678
+ # Set defaults that the hooks can utilize to ensure they always have
679
+ # the correct parameters to reproduce the previous request.
680
+ kwargs.setdefault("stream", self.stream)
681
+ kwargs.setdefault("verify", self.verify)
682
+ kwargs.setdefault("cert", self.cert)
683
+ if "proxies" not in kwargs:
684
+ kwargs["proxies"] = resolve_proxies(request, self.proxies, self.trust_env)
685
+
686
+ # It's possible that users might accidentally send a Request object.
687
+ # Guard against that specific failure case.
688
+ if isinstance(request, Request):
689
+ raise ValueError("You can only send PreparedRequests.")
690
+
691
+ # Set up variables needed for resolve_redirects and dispatching of hooks
692
+ allow_redirects = kwargs.pop("allow_redirects", True)
693
+ stream = kwargs.get("stream")
694
+ hooks = request.hooks
695
+
696
+ # Get the appropriate adapter to use
697
+ adapter = self.get_adapter(url=request.url)
698
+
699
+ # Start time (approximately) of the request
700
+ start = preferred_clock()
701
+
702
+ # Send the request
703
+ r = adapter.send(request, **kwargs)
704
+
705
+ # Total elapsed time of the request (approximately)
706
+ elapsed = preferred_clock() - start
707
+ r.elapsed = timedelta(seconds=elapsed)
708
+
709
+ # Response manipulation hooks
710
+ r = dispatch_hook("response", hooks, r, **kwargs)
711
+
712
+ # Persist cookies
713
+ if r.history:
714
+ # If the hooks create history then we want those cookies too
715
+ for resp in r.history:
716
+ extract_cookies_to_jar(self.cookies, resp.request, resp.raw)
717
+
718
+ extract_cookies_to_jar(self.cookies, request, r.raw)
719
+
720
+ # Resolve redirects if allowed.
721
+ if allow_redirects:
722
+ # Redirect resolving generator.
723
+ gen = self.resolve_redirects(r, request, **kwargs)
724
+ history = [resp for resp in gen]
725
+ else:
726
+ history = []
727
+
728
+ # Shuffle things around if there's history.
729
+ if history:
730
+ # Insert the first (original) request at the start
731
+ history.insert(0, r)
732
+ # Get the last request made
733
+ r = history.pop()
734
+ r.history = history
735
+
736
+ # If redirects aren't being followed, store the response on the Request for Response.next().
737
+ if not allow_redirects:
738
+ try:
739
+ r._next = next(
740
+ self.resolve_redirects(r, request, yield_requests=True, **kwargs)
741
+ )
742
+ except StopIteration:
743
+ pass
744
+
745
+ if not stream:
746
+ r.content
747
+
748
+ return r
749
+
750
+ def merge_environment_settings(self, url, proxies, stream, verify, cert):
751
+ """
752
+ Check the environment and merge it with some settings.
753
+
754
+ :rtype: dict
755
+ """
756
+ # Gather clues from the surrounding environment.
757
+ if self.trust_env:
758
+ # Set environment's proxies.
759
+ no_proxy = proxies.get("no_proxy") if proxies is not None else None
760
+ env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
761
+ for k, v in env_proxies.items():
762
+ proxies.setdefault(k, v)
763
+
764
+ # Look for requests environment configuration
765
+ # and be compatible with cURL.
766
+ if verify is True or verify is None:
767
+ verify = (
768
+ os.environ.get("REQUESTS_CA_BUNDLE")
769
+ or os.environ.get("CURL_CA_BUNDLE")
770
+ or verify
771
+ )
772
+
773
+ # Merge all the kwargs.
774
+ proxies = merge_setting(proxies, self.proxies)
775
+ stream = merge_setting(stream, self.stream)
776
+ verify = merge_setting(verify, self.verify)
777
+ cert = merge_setting(cert, self.cert)
778
+
779
+ return {"proxies": proxies, "stream": stream, "verify": verify, "cert": cert}
780
+
781
+ def get_adapter(self, url):
782
+ """
783
+ Returns the appropriate connection adapter for the given URL.
784
+
785
+ :rtype: requests.adapters.BaseAdapter
786
+ """
787
+ for prefix, adapter in self.adapters.items():
788
+ if url.lower().startswith(prefix.lower()):
789
+ return adapter
790
+
791
+ # Nothing matches :-/
792
+ raise InvalidSchema(f"No connection adapters were found for {url!r}")
793
+
794
+ def close(self):
795
+ """Closes all adapters and as such the session"""
796
+ for v in self.adapters.values():
797
+ v.close()
798
+
799
+ def mount(self, prefix, adapter):
800
+ """Registers a connection adapter to a prefix.
801
+
802
+ Adapters are sorted in descending order by prefix length.
803
+ """
804
+ self.adapters[prefix] = adapter
805
+ keys_to_move = [k for k in self.adapters if len(k) < len(prefix)]
806
+
807
+ for key in keys_to_move:
808
+ self.adapters[key] = self.adapters.pop(key)
809
+
810
+ def __getstate__(self):
811
+ state = {attr: getattr(self, attr, None) for attr in self.__attrs__}
812
+ return state
813
+
814
+ def __setstate__(self, state):
815
+ for attr, value in state.items():
816
+ setattr(self, attr, value)
817
+
818
+
819
+ def session():
820
+ """
821
+ Returns a :class:`Session` for context-management.
822
+
823
+ .. deprecated:: 1.0.0
824
+
825
+ This method has been deprecated since version 1.0.0 and is only kept for
826
+ backwards compatibility. New code should use :class:`~requests.sessions.Session`
827
+ to create a session. This may be removed at a future date.
828
+
829
+ :rtype: Session
830
+ """
831
+ return Session()
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/requests/structures.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ requests.structures
3
+ ~~~~~~~~~~~~~~~~~~~
4
+
5
+ Data structures that power Requests.
6
+ """
7
+
8
+ from collections import OrderedDict
9
+
10
+ from .compat import Mapping, MutableMapping
11
+
12
+
13
+ class CaseInsensitiveDict(MutableMapping):
14
+ """A case-insensitive ``dict``-like object.
15
+
16
+ Implements all methods and operations of
17
+ ``MutableMapping`` as well as dict's ``copy``. Also
18
+ provides ``lower_items``.
19
+
20
+ All keys are expected to be strings. The structure remembers the
21
+ case of the last key to be set, and ``iter(instance)``,
22
+ ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
23
+ will contain case-sensitive keys. However, querying and contains
24
+ testing is case insensitive::
25
+
26
+ cid = CaseInsensitiveDict()
27
+ cid['Accept'] = 'application/json'
28
+ cid['aCCEPT'] == 'application/json' # True
29
+ list(cid) == ['Accept'] # True
30
+
31
+ For example, ``headers['content-encoding']`` will return the
32
+ value of a ``'Content-Encoding'`` response header, regardless
33
+ of how the header name was originally stored.
34
+
35
+ If the constructor, ``.update``, or equality comparison
36
+ operations are given keys that have equal ``.lower()``s, the
37
+ behavior is undefined.
38
+ """
39
+
40
+ def __init__(self, data=None, **kwargs):
41
+ self._store = OrderedDict()
42
+ if data is None:
43
+ data = {}
44
+ self.update(data, **kwargs)
45
+
46
+ def __setitem__(self, key, value):
47
+ # Use the lowercased key for lookups, but store the actual
48
+ # key alongside the value.
49
+ self._store[key.lower()] = (key, value)
50
+
51
+ def __getitem__(self, key):
52
+ return self._store[key.lower()][1]
53
+
54
+ def __delitem__(self, key):
55
+ del self._store[key.lower()]
56
+
57
+ def __iter__(self):
58
+ return (casedkey for casedkey, mappedvalue in self._store.values())
59
+
60
+ def __len__(self):
61
+ return len(self._store)
62
+
63
+ def lower_items(self):
64
+ """Like iteritems(), but with all lowercase keys."""
65
+ return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
66
+
67
+ def __eq__(self, other):
68
+ if isinstance(other, Mapping):
69
+ other = CaseInsensitiveDict(other)
70
+ else:
71
+ return NotImplemented
72
+ # Compare insensitively
73
+ return dict(self.lower_items()) == dict(other.lower_items())
74
+
75
+ # Copy is required
76
+ def copy(self):
77
+ return CaseInsensitiveDict(self._store.values())
78
+
79
+ def __repr__(self):
80
+ return str(dict(self.items()))
81
+
82
+
83
+ class LookupDict(dict):
84
+ """Dictionary lookup object."""
85
+
86
+ def __init__(self, name=None):
87
+ self.name = name
88
+ super().__init__()
89
+
90
+ def __repr__(self):
91
+ return f"<lookup '{self.name}'>"
92
+
93
+ def __getitem__(self, key):
94
+ # We allow fall-through here, so values default to None
95
+
96
+ return self.__dict__.get(key, None)
97
+
98
+ def get(self, key, default=None):
99
+ return self.__dict__.get(key, default)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/resolvelib/__pycache__/reporters.cpython-311.pyc ADDED
Binary file (2.86 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/resolvelib/compat/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (230 Bytes). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/_stack.cpython-311.pyc ADDED
Binary file (1.15 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/_wrap.cpython-311.pyc ADDED
Binary file (3.88 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/constrain.cpython-311.pyc ADDED
Binary file (2.49 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/file_proxy.cpython-311.pyc ADDED
Binary file (4.06 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/filesize.cpython-311.pyc ADDED
Binary file (3.33 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/layout.cpython-311.pyc ADDED
Binary file (23.3 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/palette.cpython-311.pyc ADDED
Binary file (6 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/status.cpython-311.pyc ADDED
Binary file (6.78 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/table.cpython-311.pyc ADDED
Binary file (48.8 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/traceback.cpython-311.pyc ADDED
Binary file (34.6 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/rich/__pycache__/tree.cpython-311.pyc ADDED
Binary file (12.6 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/contrib/__pycache__/_appengine_environ.cpython-311.pyc ADDED
Binary file (1.97 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/contrib/__pycache__/ntlmpool.cpython-311.pyc ADDED
Binary file (6.25 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/contrib/__pycache__/pyopenssl.cpython-311.pyc ADDED
Binary file (25.8 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/contrib/__pycache__/socks.cpython-311.pyc ADDED
Binary file (8.11 kB). View file
 
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/__init__.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ # For backwards compatibility, provide imports that used to be here.
4
+ from .connection import is_connection_dropped
5
+ from .request import SKIP_HEADER, SKIPPABLE_HEADERS, make_headers
6
+ from .response import is_fp_closed
7
+ from .retry import Retry
8
+ from .ssl_ import (
9
+ ALPN_PROTOCOLS,
10
+ HAS_SNI,
11
+ IS_PYOPENSSL,
12
+ IS_SECURETRANSPORT,
13
+ PROTOCOL_TLS,
14
+ SSLContext,
15
+ assert_fingerprint,
16
+ resolve_cert_reqs,
17
+ resolve_ssl_version,
18
+ ssl_wrap_socket,
19
+ )
20
+ from .timeout import Timeout, current_time
21
+ from .url import Url, get_host, parse_url, split_first
22
+ from .wait import wait_for_read, wait_for_write
23
+
24
+ __all__ = (
25
+ "HAS_SNI",
26
+ "IS_PYOPENSSL",
27
+ "IS_SECURETRANSPORT",
28
+ "SSLContext",
29
+ "PROTOCOL_TLS",
30
+ "ALPN_PROTOCOLS",
31
+ "Retry",
32
+ "Timeout",
33
+ "Url",
34
+ "assert_fingerprint",
35
+ "current_time",
36
+ "is_connection_dropped",
37
+ "is_fp_closed",
38
+ "get_host",
39
+ "parse_url",
40
+ "make_headers",
41
+ "resolve_cert_reqs",
42
+ "resolve_ssl_version",
43
+ "split_first",
44
+ "ssl_wrap_socket",
45
+ "wait_for_read",
46
+ "wait_for_write",
47
+ "SKIP_HEADER",
48
+ "SKIPPABLE_HEADERS",
49
+ )
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/connection.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import socket
4
+
5
+ from ..contrib import _appengine_environ
6
+ from ..exceptions import LocationParseError
7
+ from ..packages import six
8
+ from .wait import NoWayToWaitForSocketError, wait_for_read
9
+
10
+
11
+ def is_connection_dropped(conn): # Platform-specific
12
+ """
13
+ Returns True if the connection is dropped and should be closed.
14
+
15
+ :param conn:
16
+ :class:`http.client.HTTPConnection` object.
17
+
18
+ Note: For platforms like AppEngine, this will always return ``False`` to
19
+ let the platform handle connection recycling transparently for us.
20
+ """
21
+ sock = getattr(conn, "sock", False)
22
+ if sock is False: # Platform-specific: AppEngine
23
+ return False
24
+ if sock is None: # Connection already closed (such as by httplib).
25
+ return True
26
+ try:
27
+ # Returns True if readable, which here means it's been dropped
28
+ return wait_for_read(sock, timeout=0.0)
29
+ except NoWayToWaitForSocketError: # Platform-specific: AppEngine
30
+ return False
31
+
32
+
33
+ # This function is copied from socket.py in the Python 2.7 standard
34
+ # library test suite. Added to its signature is only `socket_options`.
35
+ # One additional modification is that we avoid binding to IPv6 servers
36
+ # discovered in DNS if the system doesn't have IPv6 functionality.
37
+ def create_connection(
38
+ address,
39
+ timeout=socket._GLOBAL_DEFAULT_TIMEOUT,
40
+ source_address=None,
41
+ socket_options=None,
42
+ ):
43
+ """Connect to *address* and return the socket object.
44
+
45
+ Convenience function. Connect to *address* (a 2-tuple ``(host,
46
+ port)``) and return the socket object. Passing the optional
47
+ *timeout* parameter will set the timeout on the socket instance
48
+ before attempting to connect. If no *timeout* is supplied, the
49
+ global default timeout setting returned by :func:`socket.getdefaulttimeout`
50
+ is used. If *source_address* is set it must be a tuple of (host, port)
51
+ for the socket to bind as a source address before making the connection.
52
+ An host of '' or port 0 tells the OS to use the default.
53
+ """
54
+
55
+ host, port = address
56
+ if host.startswith("["):
57
+ host = host.strip("[]")
58
+ err = None
59
+
60
+ # Using the value from allowed_gai_family() in the context of getaddrinfo lets
61
+ # us select whether to work with IPv4 DNS records, IPv6 records, or both.
62
+ # The original create_connection function always returns all records.
63
+ family = allowed_gai_family()
64
+
65
+ try:
66
+ host.encode("idna")
67
+ except UnicodeError:
68
+ return six.raise_from(
69
+ LocationParseError(u"'%s', label empty or too long" % host), None
70
+ )
71
+
72
+ for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
73
+ af, socktype, proto, canonname, sa = res
74
+ sock = None
75
+ try:
76
+ sock = socket.socket(af, socktype, proto)
77
+
78
+ # If provided, set socket level options before connecting.
79
+ _set_socket_options(sock, socket_options)
80
+
81
+ if timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
82
+ sock.settimeout(timeout)
83
+ if source_address:
84
+ sock.bind(source_address)
85
+ sock.connect(sa)
86
+ return sock
87
+
88
+ except socket.error as e:
89
+ err = e
90
+ if sock is not None:
91
+ sock.close()
92
+ sock = None
93
+
94
+ if err is not None:
95
+ raise err
96
+
97
+ raise socket.error("getaddrinfo returns an empty list")
98
+
99
+
100
+ def _set_socket_options(sock, options):
101
+ if options is None:
102
+ return
103
+
104
+ for opt in options:
105
+ sock.setsockopt(*opt)
106
+
107
+
108
+ def allowed_gai_family():
109
+ """This function is designed to work in the context of
110
+ getaddrinfo, where family=socket.AF_UNSPEC is the default and
111
+ will perform a DNS search for both IPv6 and IPv4 records."""
112
+
113
+ family = socket.AF_INET
114
+ if HAS_IPV6:
115
+ family = socket.AF_UNSPEC
116
+ return family
117
+
118
+
119
+ def _has_ipv6(host):
120
+ """Returns True if the system can bind an IPv6 address."""
121
+ sock = None
122
+ has_ipv6 = False
123
+
124
+ # App Engine doesn't support IPV6 sockets and actually has a quota on the
125
+ # number of sockets that can be used, so just early out here instead of
126
+ # creating a socket needlessly.
127
+ # See https://github.com/urllib3/urllib3/issues/1446
128
+ if _appengine_environ.is_appengine_sandbox():
129
+ return False
130
+
131
+ if socket.has_ipv6:
132
+ # has_ipv6 returns true if cPython was compiled with IPv6 support.
133
+ # It does not tell us if the system has IPv6 support enabled. To
134
+ # determine that we must bind to an IPv6 address.
135
+ # https://github.com/urllib3/urllib3/pull/611
136
+ # https://bugs.python.org/issue658327
137
+ try:
138
+ sock = socket.socket(socket.AF_INET6)
139
+ sock.bind((host, 0))
140
+ has_ipv6 = True
141
+ except Exception:
142
+ pass
143
+
144
+ if sock:
145
+ sock.close()
146
+ return has_ipv6
147
+
148
+
149
+ HAS_IPV6 = _has_ipv6("::1")
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/proxy.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .ssl_ import create_urllib3_context, resolve_cert_reqs, resolve_ssl_version
2
+
3
+
4
+ def connection_requires_http_tunnel(
5
+ proxy_url=None, proxy_config=None, destination_scheme=None
6
+ ):
7
+ """
8
+ Returns True if the connection requires an HTTP CONNECT through the proxy.
9
+
10
+ :param URL proxy_url:
11
+ URL of the proxy.
12
+ :param ProxyConfig proxy_config:
13
+ Proxy configuration from poolmanager.py
14
+ :param str destination_scheme:
15
+ The scheme of the destination. (i.e https, http, etc)
16
+ """
17
+ # If we're not using a proxy, no way to use a tunnel.
18
+ if proxy_url is None:
19
+ return False
20
+
21
+ # HTTP destinations never require tunneling, we always forward.
22
+ if destination_scheme == "http":
23
+ return False
24
+
25
+ # Support for forwarding with HTTPS proxies and HTTPS destinations.
26
+ if (
27
+ proxy_url.scheme == "https"
28
+ and proxy_config
29
+ and proxy_config.use_forwarding_for_https
30
+ ):
31
+ return False
32
+
33
+ # Otherwise always use a tunnel.
34
+ return True
35
+
36
+
37
+ def create_proxy_ssl_context(
38
+ ssl_version, cert_reqs, ca_certs=None, ca_cert_dir=None, ca_cert_data=None
39
+ ):
40
+ """
41
+ Generates a default proxy ssl context if one hasn't been provided by the
42
+ user.
43
+ """
44
+ ssl_context = create_urllib3_context(
45
+ ssl_version=resolve_ssl_version(ssl_version),
46
+ cert_reqs=resolve_cert_reqs(cert_reqs),
47
+ )
48
+
49
+ if (
50
+ not ca_certs
51
+ and not ca_cert_dir
52
+ and not ca_cert_data
53
+ and hasattr(ssl_context, "load_default_certs")
54
+ ):
55
+ ssl_context.load_default_certs()
56
+
57
+ return ssl_context
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/queue.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+
3
+ from ..packages import six
4
+ from ..packages.six.moves import queue
5
+
6
+ if six.PY2:
7
+ # Queue is imported for side effects on MS Windows. See issue #229.
8
+ import Queue as _unused_module_Queue # noqa: F401
9
+
10
+
11
+ class LifoQueue(queue.Queue):
12
+ def _init(self, _):
13
+ self.queue = collections.deque()
14
+
15
+ def _qsize(self, len=len):
16
+ return len(self.queue)
17
+
18
+ def _put(self, item):
19
+ self.queue.append(item)
20
+
21
+ def _get(self):
22
+ return self.queue.pop()
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/response.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from email.errors import MultipartInvariantViolationDefect, StartBoundaryNotFoundDefect
4
+
5
+ from ..exceptions import HeaderParsingError
6
+ from ..packages.six.moves import http_client as httplib
7
+
8
+
9
+ def is_fp_closed(obj):
10
+ """
11
+ Checks whether a given file-like object is closed.
12
+
13
+ :param obj:
14
+ The file-like object to check.
15
+ """
16
+
17
+ try:
18
+ # Check `isclosed()` first, in case Python3 doesn't set `closed`.
19
+ # GH Issue #928
20
+ return obj.isclosed()
21
+ except AttributeError:
22
+ pass
23
+
24
+ try:
25
+ # Check via the official file-like-object way.
26
+ return obj.closed
27
+ except AttributeError:
28
+ pass
29
+
30
+ try:
31
+ # Check if the object is a container for another file-like object that
32
+ # gets released on exhaustion (e.g. HTTPResponse).
33
+ return obj.fp is None
34
+ except AttributeError:
35
+ pass
36
+
37
+ raise ValueError("Unable to determine whether fp is closed.")
38
+
39
+
40
+ def assert_header_parsing(headers):
41
+ """
42
+ Asserts whether all headers have been successfully parsed.
43
+ Extracts encountered errors from the result of parsing headers.
44
+
45
+ Only works on Python 3.
46
+
47
+ :param http.client.HTTPMessage headers: Headers to verify.
48
+
49
+ :raises urllib3.exceptions.HeaderParsingError:
50
+ If parsing errors are found.
51
+ """
52
+
53
+ # This will fail silently if we pass in the wrong kind of parameter.
54
+ # To make debugging easier add an explicit check.
55
+ if not isinstance(headers, httplib.HTTPMessage):
56
+ raise TypeError("expected httplib.Message, got {0}.".format(type(headers)))
57
+
58
+ defects = getattr(headers, "defects", None)
59
+ get_payload = getattr(headers, "get_payload", None)
60
+
61
+ unparsed_data = None
62
+ if get_payload:
63
+ # get_payload is actually email.message.Message.get_payload;
64
+ # we're only interested in the result if it's not a multipart message
65
+ if not headers.is_multipart():
66
+ payload = get_payload()
67
+
68
+ if isinstance(payload, (bytes, str)):
69
+ unparsed_data = payload
70
+ if defects:
71
+ # httplib is assuming a response body is available
72
+ # when parsing headers even when httplib only sends
73
+ # header data to parse_headers() This results in
74
+ # defects on multipart responses in particular.
75
+ # See: https://github.com/urllib3/urllib3/issues/800
76
+
77
+ # So we ignore the following defects:
78
+ # - StartBoundaryNotFoundDefect:
79
+ # The claimed start boundary was never found.
80
+ # - MultipartInvariantViolationDefect:
81
+ # A message claimed to be a multipart but no subparts were found.
82
+ defects = [
83
+ defect
84
+ for defect in defects
85
+ if not isinstance(
86
+ defect, (StartBoundaryNotFoundDefect, MultipartInvariantViolationDefect)
87
+ )
88
+ ]
89
+
90
+ if defects or unparsed_data:
91
+ raise HeaderParsingError(defects=defects, unparsed_data=unparsed_data)
92
+
93
+
94
+ def is_response_to_head(response):
95
+ """
96
+ Checks whether the request of a response has been a HEAD-request.
97
+ Handles the quirks of AppEngine.
98
+
99
+ :param http.client.HTTPResponse response:
100
+ Response to check if the originating request
101
+ used 'HEAD' as a method.
102
+ """
103
+ # FIXME: Can we do this somehow without accessing private httplib _method?
104
+ method = response._method
105
+ if isinstance(method, int): # Platform-specific: Appengine
106
+ return method == 3
107
+ return method.upper() == "HEAD"
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/retry.py ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import email
4
+ import logging
5
+ import re
6
+ import time
7
+ import warnings
8
+ from collections import namedtuple
9
+ from itertools import takewhile
10
+
11
+ from ..exceptions import (
12
+ ConnectTimeoutError,
13
+ InvalidHeader,
14
+ MaxRetryError,
15
+ ProtocolError,
16
+ ProxyError,
17
+ ReadTimeoutError,
18
+ ResponseError,
19
+ )
20
+ from ..packages import six
21
+
22
+ log = logging.getLogger(__name__)
23
+
24
+
25
+ # Data structure for representing the metadata of requests that result in a retry.
26
+ RequestHistory = namedtuple(
27
+ "RequestHistory", ["method", "url", "error", "status", "redirect_location"]
28
+ )
29
+
30
+
31
+ # TODO: In v2 we can remove this sentinel and metaclass with deprecated options.
32
+ _Default = object()
33
+
34
+
35
+ class _RetryMeta(type):
36
+ @property
37
+ def DEFAULT_METHOD_WHITELIST(cls):
38
+ warnings.warn(
39
+ "Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "
40
+ "will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",
41
+ DeprecationWarning,
42
+ )
43
+ return cls.DEFAULT_ALLOWED_METHODS
44
+
45
+ @DEFAULT_METHOD_WHITELIST.setter
46
+ def DEFAULT_METHOD_WHITELIST(cls, value):
47
+ warnings.warn(
48
+ "Using 'Retry.DEFAULT_METHOD_WHITELIST' is deprecated and "
49
+ "will be removed in v2.0. Use 'Retry.DEFAULT_ALLOWED_METHODS' instead",
50
+ DeprecationWarning,
51
+ )
52
+ cls.DEFAULT_ALLOWED_METHODS = value
53
+
54
+ @property
55
+ def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls):
56
+ warnings.warn(
57
+ "Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and "
58
+ "will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead",
59
+ DeprecationWarning,
60
+ )
61
+ return cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT
62
+
63
+ @DEFAULT_REDIRECT_HEADERS_BLACKLIST.setter
64
+ def DEFAULT_REDIRECT_HEADERS_BLACKLIST(cls, value):
65
+ warnings.warn(
66
+ "Using 'Retry.DEFAULT_REDIRECT_HEADERS_BLACKLIST' is deprecated and "
67
+ "will be removed in v2.0. Use 'Retry.DEFAULT_REMOVE_HEADERS_ON_REDIRECT' instead",
68
+ DeprecationWarning,
69
+ )
70
+ cls.DEFAULT_REMOVE_HEADERS_ON_REDIRECT = value
71
+
72
+ @property
73
+ def BACKOFF_MAX(cls):
74
+ warnings.warn(
75
+ "Using 'Retry.BACKOFF_MAX' is deprecated and "
76
+ "will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead",
77
+ DeprecationWarning,
78
+ )
79
+ return cls.DEFAULT_BACKOFF_MAX
80
+
81
+ @BACKOFF_MAX.setter
82
+ def BACKOFF_MAX(cls, value):
83
+ warnings.warn(
84
+ "Using 'Retry.BACKOFF_MAX' is deprecated and "
85
+ "will be removed in v2.0. Use 'Retry.DEFAULT_BACKOFF_MAX' instead",
86
+ DeprecationWarning,
87
+ )
88
+ cls.DEFAULT_BACKOFF_MAX = value
89
+
90
+
91
+ @six.add_metaclass(_RetryMeta)
92
+ class Retry(object):
93
+ """Retry configuration.
94
+
95
+ Each retry attempt will create a new Retry object with updated values, so
96
+ they can be safely reused.
97
+
98
+ Retries can be defined as a default for a pool::
99
+
100
+ retries = Retry(connect=5, read=2, redirect=5)
101
+ http = PoolManager(retries=retries)
102
+ response = http.request('GET', 'http://example.com/')
103
+
104
+ Or per-request (which overrides the default for the pool)::
105
+
106
+ response = http.request('GET', 'http://example.com/', retries=Retry(10))
107
+
108
+ Retries can be disabled by passing ``False``::
109
+
110
+ response = http.request('GET', 'http://example.com/', retries=False)
111
+
112
+ Errors will be wrapped in :class:`~urllib3.exceptions.MaxRetryError` unless
113
+ retries are disabled, in which case the causing exception will be raised.
114
+
115
+ :param int total:
116
+ Total number of retries to allow. Takes precedence over other counts.
117
+
118
+ Set to ``None`` to remove this constraint and fall back on other
119
+ counts.
120
+
121
+ Set to ``0`` to fail on the first retry.
122
+
123
+ Set to ``False`` to disable and imply ``raise_on_redirect=False``.
124
+
125
+ :param int connect:
126
+ How many connection-related errors to retry on.
127
+
128
+ These are errors raised before the request is sent to the remote server,
129
+ which we assume has not triggered the server to process the request.
130
+
131
+ Set to ``0`` to fail on the first retry of this type.
132
+
133
+ :param int read:
134
+ How many times to retry on read errors.
135
+
136
+ These errors are raised after the request was sent to the server, so the
137
+ request may have side-effects.
138
+
139
+ Set to ``0`` to fail on the first retry of this type.
140
+
141
+ :param int redirect:
142
+ How many redirects to perform. Limit this to avoid infinite redirect
143
+ loops.
144
+
145
+ A redirect is a HTTP response with a status code 301, 302, 303, 307 or
146
+ 308.
147
+
148
+ Set to ``0`` to fail on the first retry of this type.
149
+
150
+ Set to ``False`` to disable and imply ``raise_on_redirect=False``.
151
+
152
+ :param int status:
153
+ How many times to retry on bad status codes.
154
+
155
+ These are retries made on responses, where status code matches
156
+ ``status_forcelist``.
157
+
158
+ Set to ``0`` to fail on the first retry of this type.
159
+
160
+ :param int other:
161
+ How many times to retry on other errors.
162
+
163
+ Other errors are errors that are not connect, read, redirect or status errors.
164
+ These errors might be raised after the request was sent to the server, so the
165
+ request might have side-effects.
166
+
167
+ Set to ``0`` to fail on the first retry of this type.
168
+
169
+ If ``total`` is not set, it's a good idea to set this to 0 to account
170
+ for unexpected edge cases and avoid infinite retry loops.
171
+
172
+ :param iterable allowed_methods:
173
+ Set of uppercased HTTP method verbs that we should retry on.
174
+
175
+ By default, we only retry on methods which are considered to be
176
+ idempotent (multiple requests with the same parameters end with the
177
+ same state). See :attr:`Retry.DEFAULT_ALLOWED_METHODS`.
178
+
179
+ Set to a ``False`` value to retry on any verb.
180
+
181
+ .. warning::
182
+
183
+ Previously this parameter was named ``method_whitelist``, that
184
+ usage is deprecated in v1.26.0 and will be removed in v2.0.
185
+
186
+ :param iterable status_forcelist:
187
+ A set of integer HTTP status codes that we should force a retry on.
188
+ A retry is initiated if the request method is in ``allowed_methods``
189
+ and the response status code is in ``status_forcelist``.
190
+
191
+ By default, this is disabled with ``None``.
192
+
193
+ :param float backoff_factor:
194
+ A backoff factor to apply between attempts after the second try
195
+ (most errors are resolved immediately by a second try without a
196
+ delay). urllib3 will sleep for::
197
+
198
+ {backoff factor} * (2 ** ({number of total retries} - 1))
199
+
200
+ seconds. If the backoff_factor is 0.1, then :func:`.sleep` will sleep
201
+ for [0.0s, 0.2s, 0.4s, ...] between retries. It will never be longer
202
+ than :attr:`Retry.DEFAULT_BACKOFF_MAX`.
203
+
204
+ By default, backoff is disabled (set to 0).
205
+
206
+ :param bool raise_on_redirect: Whether, if the number of redirects is
207
+ exhausted, to raise a MaxRetryError, or to return a response with a
208
+ response code in the 3xx range.
209
+
210
+ :param bool raise_on_status: Similar meaning to ``raise_on_redirect``:
211
+ whether we should raise an exception, or return a response,
212
+ if status falls in ``status_forcelist`` range and retries have
213
+ been exhausted.
214
+
215
+ :param tuple history: The history of the request encountered during
216
+ each call to :meth:`~Retry.increment`. The list is in the order
217
+ the requests occurred. Each list item is of class :class:`RequestHistory`.
218
+
219
+ :param bool respect_retry_after_header:
220
+ Whether to respect Retry-After header on status codes defined as
221
+ :attr:`Retry.RETRY_AFTER_STATUS_CODES` or not.
222
+
223
+ :param iterable remove_headers_on_redirect:
224
+ Sequence of headers to remove from the request when a response
225
+ indicating a redirect is returned before firing off the redirected
226
+ request.
227
+ """
228
+
229
+ #: Default methods to be used for ``allowed_methods``
230
+ DEFAULT_ALLOWED_METHODS = frozenset(
231
+ ["HEAD", "GET", "PUT", "DELETE", "OPTIONS", "TRACE"]
232
+ )
233
+
234
+ #: Default status codes to be used for ``status_forcelist``
235
+ RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
236
+
237
+ #: Default headers to be used for ``remove_headers_on_redirect``
238
+ DEFAULT_REMOVE_HEADERS_ON_REDIRECT = frozenset(
239
+ ["Cookie", "Authorization", "Proxy-Authorization"]
240
+ )
241
+
242
+ #: Maximum backoff time.
243
+ DEFAULT_BACKOFF_MAX = 120
244
+
245
+ def __init__(
246
+ self,
247
+ total=10,
248
+ connect=None,
249
+ read=None,
250
+ redirect=None,
251
+ status=None,
252
+ other=None,
253
+ allowed_methods=_Default,
254
+ status_forcelist=None,
255
+ backoff_factor=0,
256
+ raise_on_redirect=True,
257
+ raise_on_status=True,
258
+ history=None,
259
+ respect_retry_after_header=True,
260
+ remove_headers_on_redirect=_Default,
261
+ # TODO: Deprecated, remove in v2.0
262
+ method_whitelist=_Default,
263
+ ):
264
+
265
+ if method_whitelist is not _Default:
266
+ if allowed_methods is not _Default:
267
+ raise ValueError(
268
+ "Using both 'allowed_methods' and "
269
+ "'method_whitelist' together is not allowed. "
270
+ "Instead only use 'allowed_methods'"
271
+ )
272
+ warnings.warn(
273
+ "Using 'method_whitelist' with Retry is deprecated and "
274
+ "will be removed in v2.0. Use 'allowed_methods' instead",
275
+ DeprecationWarning,
276
+ stacklevel=2,
277
+ )
278
+ allowed_methods = method_whitelist
279
+ if allowed_methods is _Default:
280
+ allowed_methods = self.DEFAULT_ALLOWED_METHODS
281
+ if remove_headers_on_redirect is _Default:
282
+ remove_headers_on_redirect = self.DEFAULT_REMOVE_HEADERS_ON_REDIRECT
283
+
284
+ self.total = total
285
+ self.connect = connect
286
+ self.read = read
287
+ self.status = status
288
+ self.other = other
289
+
290
+ if redirect is False or total is False:
291
+ redirect = 0
292
+ raise_on_redirect = False
293
+
294
+ self.redirect = redirect
295
+ self.status_forcelist = status_forcelist or set()
296
+ self.allowed_methods = allowed_methods
297
+ self.backoff_factor = backoff_factor
298
+ self.raise_on_redirect = raise_on_redirect
299
+ self.raise_on_status = raise_on_status
300
+ self.history = history or tuple()
301
+ self.respect_retry_after_header = respect_retry_after_header
302
+ self.remove_headers_on_redirect = frozenset(
303
+ [h.lower() for h in remove_headers_on_redirect]
304
+ )
305
+
306
+ def new(self, **kw):
307
+ params = dict(
308
+ total=self.total,
309
+ connect=self.connect,
310
+ read=self.read,
311
+ redirect=self.redirect,
312
+ status=self.status,
313
+ other=self.other,
314
+ status_forcelist=self.status_forcelist,
315
+ backoff_factor=self.backoff_factor,
316
+ raise_on_redirect=self.raise_on_redirect,
317
+ raise_on_status=self.raise_on_status,
318
+ history=self.history,
319
+ remove_headers_on_redirect=self.remove_headers_on_redirect,
320
+ respect_retry_after_header=self.respect_retry_after_header,
321
+ )
322
+
323
+ # TODO: If already given in **kw we use what's given to us
324
+ # If not given we need to figure out what to pass. We decide
325
+ # based on whether our class has the 'method_whitelist' property
326
+ # and if so we pass the deprecated 'method_whitelist' otherwise
327
+ # we use 'allowed_methods'. Remove in v2.0
328
+ if "method_whitelist" not in kw and "allowed_methods" not in kw:
329
+ if "method_whitelist" in self.__dict__:
330
+ warnings.warn(
331
+ "Using 'method_whitelist' with Retry is deprecated and "
332
+ "will be removed in v2.0. Use 'allowed_methods' instead",
333
+ DeprecationWarning,
334
+ )
335
+ params["method_whitelist"] = self.allowed_methods
336
+ else:
337
+ params["allowed_methods"] = self.allowed_methods
338
+
339
+ params.update(kw)
340
+ return type(self)(**params)
341
+
342
+ @classmethod
343
+ def from_int(cls, retries, redirect=True, default=None):
344
+ """Backwards-compatibility for the old retries format."""
345
+ if retries is None:
346
+ retries = default if default is not None else cls.DEFAULT
347
+
348
+ if isinstance(retries, Retry):
349
+ return retries
350
+
351
+ redirect = bool(redirect) and None
352
+ new_retries = cls(retries, redirect=redirect)
353
+ log.debug("Converted retries value: %r -> %r", retries, new_retries)
354
+ return new_retries
355
+
356
+ def get_backoff_time(self):
357
+ """Formula for computing the current backoff
358
+
359
+ :rtype: float
360
+ """
361
+ # We want to consider only the last consecutive errors sequence (Ignore redirects).
362
+ consecutive_errors_len = len(
363
+ list(
364
+ takewhile(lambda x: x.redirect_location is None, reversed(self.history))
365
+ )
366
+ )
367
+ if consecutive_errors_len <= 1:
368
+ return 0
369
+
370
+ backoff_value = self.backoff_factor * (2 ** (consecutive_errors_len - 1))
371
+ return min(self.DEFAULT_BACKOFF_MAX, backoff_value)
372
+
373
+ def parse_retry_after(self, retry_after):
374
+ # Whitespace: https://tools.ietf.org/html/rfc7230#section-3.2.4
375
+ if re.match(r"^\s*[0-9]+\s*$", retry_after):
376
+ seconds = int(retry_after)
377
+ else:
378
+ retry_date_tuple = email.utils.parsedate_tz(retry_after)
379
+ if retry_date_tuple is None:
380
+ raise InvalidHeader("Invalid Retry-After header: %s" % retry_after)
381
+ if retry_date_tuple[9] is None: # Python 2
382
+ # Assume UTC if no timezone was specified
383
+ # On Python2.7, parsedate_tz returns None for a timezone offset
384
+ # instead of 0 if no timezone is given, where mktime_tz treats
385
+ # a None timezone offset as local time.
386
+ retry_date_tuple = retry_date_tuple[:9] + (0,) + retry_date_tuple[10:]
387
+
388
+ retry_date = email.utils.mktime_tz(retry_date_tuple)
389
+ seconds = retry_date - time.time()
390
+
391
+ if seconds < 0:
392
+ seconds = 0
393
+
394
+ return seconds
395
+
396
+ def get_retry_after(self, response):
397
+ """Get the value of Retry-After in seconds."""
398
+
399
+ retry_after = response.headers.get("Retry-After")
400
+
401
+ if retry_after is None:
402
+ return None
403
+
404
+ return self.parse_retry_after(retry_after)
405
+
406
+ def sleep_for_retry(self, response=None):
407
+ retry_after = self.get_retry_after(response)
408
+ if retry_after:
409
+ time.sleep(retry_after)
410
+ return True
411
+
412
+ return False
413
+
414
+ def _sleep_backoff(self):
415
+ backoff = self.get_backoff_time()
416
+ if backoff <= 0:
417
+ return
418
+ time.sleep(backoff)
419
+
420
+ def sleep(self, response=None):
421
+ """Sleep between retry attempts.
422
+
423
+ This method will respect a server's ``Retry-After`` response header
424
+ and sleep the duration of the time requested. If that is not present, it
425
+ will use an exponential backoff. By default, the backoff factor is 0 and
426
+ this method will return immediately.
427
+ """
428
+
429
+ if self.respect_retry_after_header and response:
430
+ slept = self.sleep_for_retry(response)
431
+ if slept:
432
+ return
433
+
434
+ self._sleep_backoff()
435
+
436
+ def _is_connection_error(self, err):
437
+ """Errors when we're fairly sure that the server did not receive the
438
+ request, so it should be safe to retry.
439
+ """
440
+ if isinstance(err, ProxyError):
441
+ err = err.original_error
442
+ return isinstance(err, ConnectTimeoutError)
443
+
444
+ def _is_read_error(self, err):
445
+ """Errors that occur after the request has been started, so we should
446
+ assume that the server began processing it.
447
+ """
448
+ return isinstance(err, (ReadTimeoutError, ProtocolError))
449
+
450
+ def _is_method_retryable(self, method):
451
+ """Checks if a given HTTP method should be retried upon, depending if
452
+ it is included in the allowed_methods
453
+ """
454
+ # TODO: For now favor if the Retry implementation sets its own method_whitelist
455
+ # property outside of our constructor to avoid breaking custom implementations.
456
+ if "method_whitelist" in self.__dict__:
457
+ warnings.warn(
458
+ "Using 'method_whitelist' with Retry is deprecated and "
459
+ "will be removed in v2.0. Use 'allowed_methods' instead",
460
+ DeprecationWarning,
461
+ )
462
+ allowed_methods = self.method_whitelist
463
+ else:
464
+ allowed_methods = self.allowed_methods
465
+
466
+ if allowed_methods and method.upper() not in allowed_methods:
467
+ return False
468
+ return True
469
+
470
+ def is_retry(self, method, status_code, has_retry_after=False):
471
+ """Is this method/status code retryable? (Based on allowlists and control
472
+ variables such as the number of total retries to allow, whether to
473
+ respect the Retry-After header, whether this header is present, and
474
+ whether the returned status code is on the list of status codes to
475
+ be retried upon on the presence of the aforementioned header)
476
+ """
477
+ if not self._is_method_retryable(method):
478
+ return False
479
+
480
+ if self.status_forcelist and status_code in self.status_forcelist:
481
+ return True
482
+
483
+ return (
484
+ self.total
485
+ and self.respect_retry_after_header
486
+ and has_retry_after
487
+ and (status_code in self.RETRY_AFTER_STATUS_CODES)
488
+ )
489
+
490
+ def is_exhausted(self):
491
+ """Are we out of retries?"""
492
+ retry_counts = (
493
+ self.total,
494
+ self.connect,
495
+ self.read,
496
+ self.redirect,
497
+ self.status,
498
+ self.other,
499
+ )
500
+ retry_counts = list(filter(None, retry_counts))
501
+ if not retry_counts:
502
+ return False
503
+
504
+ return min(retry_counts) < 0
505
+
506
+ def increment(
507
+ self,
508
+ method=None,
509
+ url=None,
510
+ response=None,
511
+ error=None,
512
+ _pool=None,
513
+ _stacktrace=None,
514
+ ):
515
+ """Return a new Retry object with incremented retry counters.
516
+
517
+ :param response: A response object, or None, if the server did not
518
+ return a response.
519
+ :type response: :class:`~urllib3.response.HTTPResponse`
520
+ :param Exception error: An error encountered during the request, or
521
+ None if the response was received successfully.
522
+
523
+ :return: A new ``Retry`` object.
524
+ """
525
+ if self.total is False and error:
526
+ # Disabled, indicate to re-raise the error.
527
+ raise six.reraise(type(error), error, _stacktrace)
528
+
529
+ total = self.total
530
+ if total is not None:
531
+ total -= 1
532
+
533
+ connect = self.connect
534
+ read = self.read
535
+ redirect = self.redirect
536
+ status_count = self.status
537
+ other = self.other
538
+ cause = "unknown"
539
+ status = None
540
+ redirect_location = None
541
+
542
+ if error and self._is_connection_error(error):
543
+ # Connect retry?
544
+ if connect is False:
545
+ raise six.reraise(type(error), error, _stacktrace)
546
+ elif connect is not None:
547
+ connect -= 1
548
+
549
+ elif error and self._is_read_error(error):
550
+ # Read retry?
551
+ if read is False or not self._is_method_retryable(method):
552
+ raise six.reraise(type(error), error, _stacktrace)
553
+ elif read is not None:
554
+ read -= 1
555
+
556
+ elif error:
557
+ # Other retry?
558
+ if other is not None:
559
+ other -= 1
560
+
561
+ elif response and response.get_redirect_location():
562
+ # Redirect retry?
563
+ if redirect is not None:
564
+ redirect -= 1
565
+ cause = "too many redirects"
566
+ redirect_location = response.get_redirect_location()
567
+ status = response.status
568
+
569
+ else:
570
+ # Incrementing because of a server error like a 500 in
571
+ # status_forcelist and the given method is in the allowed_methods
572
+ cause = ResponseError.GENERIC_ERROR
573
+ if response and response.status:
574
+ if status_count is not None:
575
+ status_count -= 1
576
+ cause = ResponseError.SPECIFIC_ERROR.format(status_code=response.status)
577
+ status = response.status
578
+
579
+ history = self.history + (
580
+ RequestHistory(method, url, error, status, redirect_location),
581
+ )
582
+
583
+ new_retry = self.new(
584
+ total=total,
585
+ connect=connect,
586
+ read=read,
587
+ redirect=redirect,
588
+ status=status_count,
589
+ other=other,
590
+ history=history,
591
+ )
592
+
593
+ if new_retry.is_exhausted():
594
+ raise MaxRetryError(_pool, url, error or ResponseError(cause))
595
+
596
+ log.debug("Incremented Retry for (url='%s'): %r", url, new_retry)
597
+
598
+ return new_retry
599
+
600
+ def __repr__(self):
601
+ return (
602
+ "{cls.__name__}(total={self.total}, connect={self.connect}, "
603
+ "read={self.read}, redirect={self.redirect}, status={self.status})"
604
+ ).format(cls=type(self), self=self)
605
+
606
+ def __getattr__(self, item):
607
+ if item == "method_whitelist":
608
+ # TODO: Remove this deprecated alias in v2.0
609
+ warnings.warn(
610
+ "Using 'method_whitelist' with Retry is deprecated and "
611
+ "will be removed in v2.0. Use 'allowed_methods' instead",
612
+ DeprecationWarning,
613
+ )
614
+ return self.allowed_methods
615
+ try:
616
+ return getattr(super(Retry, self), item)
617
+ except AttributeError:
618
+ return getattr(Retry, item)
619
+
620
+
621
+ # For backwards compatibility (equivalent to pre-v1.9):
622
+ Retry.DEFAULT = Retry(3)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/ssl_.py ADDED
@@ -0,0 +1,504 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import hashlib
4
+ import hmac
5
+ import os
6
+ import sys
7
+ import warnings
8
+ from binascii import hexlify, unhexlify
9
+
10
+ from ..exceptions import (
11
+ InsecurePlatformWarning,
12
+ ProxySchemeUnsupported,
13
+ SNIMissingWarning,
14
+ SSLError,
15
+ )
16
+ from ..packages import six
17
+ from .url import BRACELESS_IPV6_ADDRZ_RE, IPV4_RE
18
+
19
+ SSLContext = None
20
+ SSLTransport = None
21
+ HAS_SNI = False
22
+ IS_PYOPENSSL = False
23
+ IS_SECURETRANSPORT = False
24
+ ALPN_PROTOCOLS = ["http/1.1"]
25
+
26
+ # Maps the length of a digest to a possible hash function producing this digest
27
+ HASHFUNC_MAP = {
28
+ length: getattr(hashlib, algorithm, None)
29
+ for length, algorithm in ((32, "md5"), (40, "sha1"), (64, "sha256"))
30
+ }
31
+
32
+
33
+ def _const_compare_digest_backport(a, b):
34
+ """
35
+ Compare two digests of equal length in constant time.
36
+
37
+ The digests must be of type str/bytes.
38
+ Returns True if the digests match, and False otherwise.
39
+ """
40
+ result = abs(len(a) - len(b))
41
+ for left, right in zip(bytearray(a), bytearray(b)):
42
+ result |= left ^ right
43
+ return result == 0
44
+
45
+
46
+ _const_compare_digest = getattr(hmac, "compare_digest", _const_compare_digest_backport)
47
+
48
+ try: # Test for SSL features
49
+ import ssl
50
+ from ssl import CERT_REQUIRED, wrap_socket
51
+ except ImportError:
52
+ pass
53
+
54
+ try:
55
+ from ssl import HAS_SNI # Has SNI?
56
+ except ImportError:
57
+ pass
58
+
59
+ try:
60
+ from .ssltransport import SSLTransport
61
+ except ImportError:
62
+ pass
63
+
64
+
65
+ try: # Platform-specific: Python 3.6
66
+ from ssl import PROTOCOL_TLS
67
+
68
+ PROTOCOL_SSLv23 = PROTOCOL_TLS
69
+ except ImportError:
70
+ try:
71
+ from ssl import PROTOCOL_SSLv23 as PROTOCOL_TLS
72
+
73
+ PROTOCOL_SSLv23 = PROTOCOL_TLS
74
+ except ImportError:
75
+ PROTOCOL_SSLv23 = PROTOCOL_TLS = 2
76
+
77
+ try:
78
+ from ssl import PROTOCOL_TLS_CLIENT
79
+ except ImportError:
80
+ PROTOCOL_TLS_CLIENT = PROTOCOL_TLS
81
+
82
+
83
+ try:
84
+ from ssl import OP_NO_COMPRESSION, OP_NO_SSLv2, OP_NO_SSLv3
85
+ except ImportError:
86
+ OP_NO_SSLv2, OP_NO_SSLv3 = 0x1000000, 0x2000000
87
+ OP_NO_COMPRESSION = 0x20000
88
+
89
+
90
+ try: # OP_NO_TICKET was added in Python 3.6
91
+ from ssl import OP_NO_TICKET
92
+ except ImportError:
93
+ OP_NO_TICKET = 0x4000
94
+
95
+
96
+ # A secure default.
97
+ # Sources for more information on TLS ciphers:
98
+ #
99
+ # - https://wiki.mozilla.org/Security/Server_Side_TLS
100
+ # - https://www.ssllabs.com/projects/best-practices/index.html
101
+ # - https://hynek.me/articles/hardening-your-web-servers-ssl-ciphers/
102
+ #
103
+ # The general intent is:
104
+ # - prefer cipher suites that offer perfect forward secrecy (DHE/ECDHE),
105
+ # - prefer ECDHE over DHE for better performance,
106
+ # - prefer any AES-GCM and ChaCha20 over any AES-CBC for better performance and
107
+ # security,
108
+ # - prefer AES-GCM over ChaCha20 because hardware-accelerated AES is common,
109
+ # - disable NULL authentication, MD5 MACs, DSS, and other
110
+ # insecure ciphers for security reasons.
111
+ # - NOTE: TLS 1.3 cipher suites are managed through a different interface
112
+ # not exposed by CPython (yet!) and are enabled by default if they're available.
113
+ DEFAULT_CIPHERS = ":".join(
114
+ [
115
+ "ECDHE+AESGCM",
116
+ "ECDHE+CHACHA20",
117
+ "DHE+AESGCM",
118
+ "DHE+CHACHA20",
119
+ "ECDH+AESGCM",
120
+ "DH+AESGCM",
121
+ "ECDH+AES",
122
+ "DH+AES",
123
+ "RSA+AESGCM",
124
+ "RSA+AES",
125
+ "!aNULL",
126
+ "!eNULL",
127
+ "!MD5",
128
+ "!DSS",
129
+ ]
130
+ )
131
+
132
+ try:
133
+ from ssl import SSLContext # Modern SSL?
134
+ except ImportError:
135
+
136
+ class SSLContext(object): # Platform-specific: Python 2
137
+ def __init__(self, protocol_version):
138
+ self.protocol = protocol_version
139
+ # Use default values from a real SSLContext
140
+ self.check_hostname = False
141
+ self.verify_mode = ssl.CERT_NONE
142
+ self.ca_certs = None
143
+ self.options = 0
144
+ self.certfile = None
145
+ self.keyfile = None
146
+ self.ciphers = None
147
+
148
+ def load_cert_chain(self, certfile, keyfile):
149
+ self.certfile = certfile
150
+ self.keyfile = keyfile
151
+
152
+ def load_verify_locations(self, cafile=None, capath=None, cadata=None):
153
+ self.ca_certs = cafile
154
+
155
+ if capath is not None:
156
+ raise SSLError("CA directories not supported in older Pythons")
157
+
158
+ if cadata is not None:
159
+ raise SSLError("CA data not supported in older Pythons")
160
+
161
+ def set_ciphers(self, cipher_suite):
162
+ self.ciphers = cipher_suite
163
+
164
+ def wrap_socket(self, socket, server_hostname=None, server_side=False):
165
+ warnings.warn(
166
+ "A true SSLContext object is not available. This prevents "
167
+ "urllib3 from configuring SSL appropriately and may cause "
168
+ "certain SSL connections to fail. You can upgrade to a newer "
169
+ "version of Python to solve this. For more information, see "
170
+ "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
171
+ "#ssl-warnings",
172
+ InsecurePlatformWarning,
173
+ )
174
+ kwargs = {
175
+ "keyfile": self.keyfile,
176
+ "certfile": self.certfile,
177
+ "ca_certs": self.ca_certs,
178
+ "cert_reqs": self.verify_mode,
179
+ "ssl_version": self.protocol,
180
+ "server_side": server_side,
181
+ }
182
+ return wrap_socket(socket, ciphers=self.ciphers, **kwargs)
183
+
184
+
185
+ def assert_fingerprint(cert, fingerprint):
186
+ """
187
+ Checks if given fingerprint matches the supplied certificate.
188
+
189
+ :param cert:
190
+ Certificate as bytes object.
191
+ :param fingerprint:
192
+ Fingerprint as string of hexdigits, can be interspersed by colons.
193
+ """
194
+
195
+ fingerprint = fingerprint.replace(":", "").lower()
196
+ digest_length = len(fingerprint)
197
+ if digest_length not in HASHFUNC_MAP:
198
+ raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint))
199
+ hashfunc = HASHFUNC_MAP.get(digest_length)
200
+ if hashfunc is None:
201
+ raise SSLError(
202
+ "Hash function implementation unavailable for fingerprint length: {0}".format(
203
+ digest_length
204
+ )
205
+ )
206
+
207
+ # We need encode() here for py32; works on py2 and p33.
208
+ fingerprint_bytes = unhexlify(fingerprint.encode())
209
+
210
+ cert_digest = hashfunc(cert).digest()
211
+
212
+ if not _const_compare_digest(cert_digest, fingerprint_bytes):
213
+ raise SSLError(
214
+ 'Fingerprints did not match. Expected "{0}", got "{1}".'.format(
215
+ fingerprint, hexlify(cert_digest)
216
+ )
217
+ )
218
+
219
+
220
+ def resolve_cert_reqs(candidate):
221
+ """
222
+ Resolves the argument to a numeric constant, which can be passed to
223
+ the wrap_socket function/method from the ssl module.
224
+ Defaults to :data:`ssl.CERT_REQUIRED`.
225
+ If given a string it is assumed to be the name of the constant in the
226
+ :mod:`ssl` module or its abbreviation.
227
+ (So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
228
+ If it's neither `None` nor a string we assume it is already the numeric
229
+ constant which can directly be passed to wrap_socket.
230
+ """
231
+ if candidate is None:
232
+ return CERT_REQUIRED
233
+
234
+ if isinstance(candidate, str):
235
+ res = getattr(ssl, candidate, None)
236
+ if res is None:
237
+ res = getattr(ssl, "CERT_" + candidate)
238
+ return res
239
+
240
+ return candidate
241
+
242
+
243
+ def resolve_ssl_version(candidate):
244
+ """
245
+ like resolve_cert_reqs
246
+ """
247
+ if candidate is None:
248
+ return PROTOCOL_TLS
249
+
250
+ if isinstance(candidate, str):
251
+ res = getattr(ssl, candidate, None)
252
+ if res is None:
253
+ res = getattr(ssl, "PROTOCOL_" + candidate)
254
+ return res
255
+
256
+ return candidate
257
+
258
+
259
+ def create_urllib3_context(
260
+ ssl_version=None, cert_reqs=None, options=None, ciphers=None
261
+ ):
262
+ """All arguments have the same meaning as ``ssl_wrap_socket``.
263
+
264
+ By default, this function does a lot of the same work that
265
+ ``ssl.create_default_context`` does on Python 3.4+. It:
266
+
267
+ - Disables SSLv2, SSLv3, and compression
268
+ - Sets a restricted set of server ciphers
269
+
270
+ If you wish to enable SSLv3, you can do::
271
+
272
+ from pip._vendor.urllib3.util import ssl_
273
+ context = ssl_.create_urllib3_context()
274
+ context.options &= ~ssl_.OP_NO_SSLv3
275
+
276
+ You can do the same to enable compression (substituting ``COMPRESSION``
277
+ for ``SSLv3`` in the last line above).
278
+
279
+ :param ssl_version:
280
+ The desired protocol version to use. This will default to
281
+ PROTOCOL_SSLv23 which will negotiate the highest protocol that both
282
+ the server and your installation of OpenSSL support.
283
+ :param cert_reqs:
284
+ Whether to require the certificate verification. This defaults to
285
+ ``ssl.CERT_REQUIRED``.
286
+ :param options:
287
+ Specific OpenSSL options. These default to ``ssl.OP_NO_SSLv2``,
288
+ ``ssl.OP_NO_SSLv3``, ``ssl.OP_NO_COMPRESSION``, and ``ssl.OP_NO_TICKET``.
289
+ :param ciphers:
290
+ Which cipher suites to allow the server to select.
291
+ :returns:
292
+ Constructed SSLContext object with specified options
293
+ :rtype: SSLContext
294
+ """
295
+ # PROTOCOL_TLS is deprecated in Python 3.10
296
+ if not ssl_version or ssl_version == PROTOCOL_TLS:
297
+ ssl_version = PROTOCOL_TLS_CLIENT
298
+
299
+ context = SSLContext(ssl_version)
300
+
301
+ context.set_ciphers(ciphers or DEFAULT_CIPHERS)
302
+
303
+ # Setting the default here, as we may have no ssl module on import
304
+ cert_reqs = ssl.CERT_REQUIRED if cert_reqs is None else cert_reqs
305
+
306
+ if options is None:
307
+ options = 0
308
+ # SSLv2 is easily broken and is considered harmful and dangerous
309
+ options |= OP_NO_SSLv2
310
+ # SSLv3 has several problems and is now dangerous
311
+ options |= OP_NO_SSLv3
312
+ # Disable compression to prevent CRIME attacks for OpenSSL 1.0+
313
+ # (issue #309)
314
+ options |= OP_NO_COMPRESSION
315
+ # TLSv1.2 only. Unless set explicitly, do not request tickets.
316
+ # This may save some bandwidth on wire, and although the ticket is encrypted,
317
+ # there is a risk associated with it being on wire,
318
+ # if the server is not rotating its ticketing keys properly.
319
+ options |= OP_NO_TICKET
320
+
321
+ context.options |= options
322
+
323
+ # Enable post-handshake authentication for TLS 1.3, see GH #1634. PHA is
324
+ # necessary for conditional client cert authentication with TLS 1.3.
325
+ # The attribute is None for OpenSSL <= 1.1.0 or does not exist in older
326
+ # versions of Python. We only enable on Python 3.7.4+ or if certificate
327
+ # verification is enabled to work around Python issue #37428
328
+ # See: https://bugs.python.org/issue37428
329
+ if (cert_reqs == ssl.CERT_REQUIRED or sys.version_info >= (3, 7, 4)) and getattr(
330
+ context, "post_handshake_auth", None
331
+ ) is not None:
332
+ context.post_handshake_auth = True
333
+
334
+ def disable_check_hostname():
335
+ if (
336
+ getattr(context, "check_hostname", None) is not None
337
+ ): # Platform-specific: Python 3.2
338
+ # We do our own verification, including fingerprints and alternative
339
+ # hostnames. So disable it here
340
+ context.check_hostname = False
341
+
342
+ # The order of the below lines setting verify_mode and check_hostname
343
+ # matter due to safe-guards SSLContext has to prevent an SSLContext with
344
+ # check_hostname=True, verify_mode=NONE/OPTIONAL. This is made even more
345
+ # complex because we don't know whether PROTOCOL_TLS_CLIENT will be used
346
+ # or not so we don't know the initial state of the freshly created SSLContext.
347
+ if cert_reqs == ssl.CERT_REQUIRED:
348
+ context.verify_mode = cert_reqs
349
+ disable_check_hostname()
350
+ else:
351
+ disable_check_hostname()
352
+ context.verify_mode = cert_reqs
353
+
354
+ # Enable logging of TLS session keys via defacto standard environment variable
355
+ # 'SSLKEYLOGFILE', if the feature is available (Python 3.8+). Skip empty values.
356
+ if hasattr(context, "keylog_filename"):
357
+ sslkeylogfile = os.environ.get("SSLKEYLOGFILE")
358
+ if sslkeylogfile:
359
+ context.keylog_filename = sslkeylogfile
360
+
361
+ return context
362
+
363
+
364
+ def ssl_wrap_socket(
365
+ sock,
366
+ keyfile=None,
367
+ certfile=None,
368
+ cert_reqs=None,
369
+ ca_certs=None,
370
+ server_hostname=None,
371
+ ssl_version=None,
372
+ ciphers=None,
373
+ ssl_context=None,
374
+ ca_cert_dir=None,
375
+ key_password=None,
376
+ ca_cert_data=None,
377
+ tls_in_tls=False,
378
+ ):
379
+ """
380
+ All arguments except for server_hostname, ssl_context, and ca_cert_dir have
381
+ the same meaning as they do when using :func:`ssl.wrap_socket`.
382
+
383
+ :param server_hostname:
384
+ When SNI is supported, the expected hostname of the certificate
385
+ :param ssl_context:
386
+ A pre-made :class:`SSLContext` object. If none is provided, one will
387
+ be created using :func:`create_urllib3_context`.
388
+ :param ciphers:
389
+ A string of ciphers we wish the client to support.
390
+ :param ca_cert_dir:
391
+ A directory containing CA certificates in multiple separate files, as
392
+ supported by OpenSSL's -CApath flag or the capath argument to
393
+ SSLContext.load_verify_locations().
394
+ :param key_password:
395
+ Optional password if the keyfile is encrypted.
396
+ :param ca_cert_data:
397
+ Optional string containing CA certificates in PEM format suitable for
398
+ passing as the cadata parameter to SSLContext.load_verify_locations()
399
+ :param tls_in_tls:
400
+ Use SSLTransport to wrap the existing socket.
401
+ """
402
+ context = ssl_context
403
+ if context is None:
404
+ # Note: This branch of code and all the variables in it are no longer
405
+ # used by urllib3 itself. We should consider deprecating and removing
406
+ # this code.
407
+ context = create_urllib3_context(ssl_version, cert_reqs, ciphers=ciphers)
408
+
409
+ if ca_certs or ca_cert_dir or ca_cert_data:
410
+ try:
411
+ context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data)
412
+ except (IOError, OSError) as e:
413
+ raise SSLError(e)
414
+
415
+ elif ssl_context is None and hasattr(context, "load_default_certs"):
416
+ # try to load OS default certs; works well on Windows (require Python3.4+)
417
+ context.load_default_certs()
418
+
419
+ # Attempt to detect if we get the goofy behavior of the
420
+ # keyfile being encrypted and OpenSSL asking for the
421
+ # passphrase via the terminal and instead error out.
422
+ if keyfile and key_password is None and _is_key_file_encrypted(keyfile):
423
+ raise SSLError("Client private key is encrypted, password is required")
424
+
425
+ if certfile:
426
+ if key_password is None:
427
+ context.load_cert_chain(certfile, keyfile)
428
+ else:
429
+ context.load_cert_chain(certfile, keyfile, key_password)
430
+
431
+ try:
432
+ if hasattr(context, "set_alpn_protocols"):
433
+ context.set_alpn_protocols(ALPN_PROTOCOLS)
434
+ except NotImplementedError: # Defensive: in CI, we always have set_alpn_protocols
435
+ pass
436
+
437
+ # If we detect server_hostname is an IP address then the SNI
438
+ # extension should not be used according to RFC3546 Section 3.1
439
+ use_sni_hostname = server_hostname and not is_ipaddress(server_hostname)
440
+ # SecureTransport uses server_hostname in certificate verification.
441
+ send_sni = (use_sni_hostname and HAS_SNI) or (
442
+ IS_SECURETRANSPORT and server_hostname
443
+ )
444
+ # Do not warn the user if server_hostname is an invalid SNI hostname.
445
+ if not HAS_SNI and use_sni_hostname:
446
+ warnings.warn(
447
+ "An HTTPS request has been made, but the SNI (Server Name "
448
+ "Indication) extension to TLS is not available on this platform. "
449
+ "This may cause the server to present an incorrect TLS "
450
+ "certificate, which can cause validation failures. You can upgrade to "
451
+ "a newer version of Python to solve this. For more information, see "
452
+ "https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html"
453
+ "#ssl-warnings",
454
+ SNIMissingWarning,
455
+ )
456
+
457
+ if send_sni:
458
+ ssl_sock = _ssl_wrap_socket_impl(
459
+ sock, context, tls_in_tls, server_hostname=server_hostname
460
+ )
461
+ else:
462
+ ssl_sock = _ssl_wrap_socket_impl(sock, context, tls_in_tls)
463
+ return ssl_sock
464
+
465
+
466
+ def is_ipaddress(hostname):
467
+ """Detects whether the hostname given is an IPv4 or IPv6 address.
468
+ Also detects IPv6 addresses with Zone IDs.
469
+
470
+ :param str hostname: Hostname to examine.
471
+ :return: True if the hostname is an IP address, False otherwise.
472
+ """
473
+ if not six.PY2 and isinstance(hostname, bytes):
474
+ # IDN A-label bytes are ASCII compatible.
475
+ hostname = hostname.decode("ascii")
476
+ return bool(IPV4_RE.match(hostname) or BRACELESS_IPV6_ADDRZ_RE.match(hostname))
477
+
478
+
479
+ def _is_key_file_encrypted(key_file):
480
+ """Detects if a key file is encrypted or not."""
481
+ with open(key_file, "r") as f:
482
+ for line in f:
483
+ # Look for Proc-Type: 4,ENCRYPTED
484
+ if "ENCRYPTED" in line:
485
+ return True
486
+
487
+ return False
488
+
489
+
490
+ def _ssl_wrap_socket_impl(sock, ssl_context, tls_in_tls, server_hostname=None):
491
+ if tls_in_tls:
492
+ if not SSLTransport:
493
+ # Import error, ssl is not available.
494
+ raise ProxySchemeUnsupported(
495
+ "TLS in TLS requires support for the 'ssl' module"
496
+ )
497
+
498
+ SSLTransport._validate_ssl_context_for_tls_in_tls(ssl_context)
499
+ return SSLTransport(sock, ssl_context, server_hostname)
500
+
501
+ if server_hostname:
502
+ return ssl_context.wrap_socket(sock, server_hostname=server_hostname)
503
+ else:
504
+ return ssl_context.wrap_socket(sock)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pip/_vendor/urllib3/util/url.py ADDED
@@ -0,0 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ import re
4
+ from collections import namedtuple
5
+
6
+ from ..exceptions import LocationParseError
7
+ from ..packages import six
8
+
9
+ url_attrs = ["scheme", "auth", "host", "port", "path", "query", "fragment"]
10
+
11
+ # We only want to normalize urls with an HTTP(S) scheme.
12
+ # urllib3 infers URLs without a scheme (None) to be http.
13
+ NORMALIZABLE_SCHEMES = ("http", "https", None)
14
+
15
+ # Almost all of these patterns were derived from the
16
+ # 'rfc3986' module: https://github.com/python-hyper/rfc3986
17
+ PERCENT_RE = re.compile(r"%[a-fA-F0-9]{2}")
18
+ SCHEME_RE = re.compile(r"^(?:[a-zA-Z][a-zA-Z0-9+-]*:|/)")
19
+ URI_RE = re.compile(
20
+ r"^(?:([a-zA-Z][a-zA-Z0-9+.-]*):)?"
21
+ r"(?://([^\\/?#]*))?"
22
+ r"([^?#]*)"
23
+ r"(?:\?([^#]*))?"
24
+ r"(?:#(.*))?$",
25
+ re.UNICODE | re.DOTALL,
26
+ )
27
+
28
+ IPV4_PAT = r"(?:[0-9]{1,3}\.){3}[0-9]{1,3}"
29
+ HEX_PAT = "[0-9A-Fa-f]{1,4}"
30
+ LS32_PAT = "(?:{hex}:{hex}|{ipv4})".format(hex=HEX_PAT, ipv4=IPV4_PAT)
31
+ _subs = {"hex": HEX_PAT, "ls32": LS32_PAT}
32
+ _variations = [
33
+ # 6( h16 ":" ) ls32
34
+ "(?:%(hex)s:){6}%(ls32)s",
35
+ # "::" 5( h16 ":" ) ls32
36
+ "::(?:%(hex)s:){5}%(ls32)s",
37
+ # [ h16 ] "::" 4( h16 ":" ) ls32
38
+ "(?:%(hex)s)?::(?:%(hex)s:){4}%(ls32)s",
39
+ # [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
40
+ "(?:(?:%(hex)s:)?%(hex)s)?::(?:%(hex)s:){3}%(ls32)s",
41
+ # [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
42
+ "(?:(?:%(hex)s:){0,2}%(hex)s)?::(?:%(hex)s:){2}%(ls32)s",
43
+ # [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
44
+ "(?:(?:%(hex)s:){0,3}%(hex)s)?::%(hex)s:%(ls32)s",
45
+ # [ *4( h16 ":" ) h16 ] "::" ls32
46
+ "(?:(?:%(hex)s:){0,4}%(hex)s)?::%(ls32)s",
47
+ # [ *5( h16 ":" ) h16 ] "::" h16
48
+ "(?:(?:%(hex)s:){0,5}%(hex)s)?::%(hex)s",
49
+ # [ *6( h16 ":" ) h16 ] "::"
50
+ "(?:(?:%(hex)s:){0,6}%(hex)s)?::",
51
+ ]
52
+
53
+ UNRESERVED_PAT = r"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._\-~"
54
+ IPV6_PAT = "(?:" + "|".join([x % _subs for x in _variations]) + ")"
55
+ ZONE_ID_PAT = "(?:%25|%)(?:[" + UNRESERVED_PAT + "]|%[a-fA-F0-9]{2})+"
56
+ IPV6_ADDRZ_PAT = r"\[" + IPV6_PAT + r"(?:" + ZONE_ID_PAT + r")?\]"
57
+ REG_NAME_PAT = r"(?:[^\[\]%:/?#]|%[a-fA-F0-9]{2})*"
58
+ TARGET_RE = re.compile(r"^(/[^?#]*)(?:\?([^#]*))?(?:#.*)?$")
59
+
60
+ IPV4_RE = re.compile("^" + IPV4_PAT + "$")
61
+ IPV6_RE = re.compile("^" + IPV6_PAT + "$")
62
+ IPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT + "$")
63
+ BRACELESS_IPV6_ADDRZ_RE = re.compile("^" + IPV6_ADDRZ_PAT[2:-2] + "$")
64
+ ZONE_ID_RE = re.compile("(" + ZONE_ID_PAT + r")\]$")
65
+
66
+ _HOST_PORT_PAT = ("^(%s|%s|%s)(?::0*?(|0|[1-9][0-9]{0,4}))?$") % (
67
+ REG_NAME_PAT,
68
+ IPV4_PAT,
69
+ IPV6_ADDRZ_PAT,
70
+ )
71
+ _HOST_PORT_RE = re.compile(_HOST_PORT_PAT, re.UNICODE | re.DOTALL)
72
+
73
+ UNRESERVED_CHARS = set(
74
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-~"
75
+ )
76
+ SUB_DELIM_CHARS = set("!$&'()*+,;=")
77
+ USERINFO_CHARS = UNRESERVED_CHARS | SUB_DELIM_CHARS | {":"}
78
+ PATH_CHARS = USERINFO_CHARS | {"@", "/"}
79
+ QUERY_CHARS = FRAGMENT_CHARS = PATH_CHARS | {"?"}
80
+
81
+
82
+ class Url(namedtuple("Url", url_attrs)):
83
+ """
84
+ Data structure for representing an HTTP URL. Used as a return value for
85
+ :func:`parse_url`. Both the scheme and host are normalized as they are
86
+ both case-insensitive according to RFC 3986.
87
+ """
88
+
89
+ __slots__ = ()
90
+
91
+ def __new__(
92
+ cls,
93
+ scheme=None,
94
+ auth=None,
95
+ host=None,
96
+ port=None,
97
+ path=None,
98
+ query=None,
99
+ fragment=None,
100
+ ):
101
+ if path and not path.startswith("/"):
102
+ path = "/" + path
103
+ if scheme is not None:
104
+ scheme = scheme.lower()
105
+ return super(Url, cls).__new__(
106
+ cls, scheme, auth, host, port, path, query, fragment
107
+ )
108
+
109
+ @property
110
+ def hostname(self):
111
+ """For backwards-compatibility with urlparse. We're nice like that."""
112
+ return self.host
113
+
114
+ @property
115
+ def request_uri(self):
116
+ """Absolute path including the query string."""
117
+ uri = self.path or "/"
118
+
119
+ if self.query is not None:
120
+ uri += "?" + self.query
121
+
122
+ return uri
123
+
124
+ @property
125
+ def netloc(self):
126
+ """Network location including host and port"""
127
+ if self.port:
128
+ return "%s:%d" % (self.host, self.port)
129
+ return self.host
130
+
131
+ @property
132
+ def url(self):
133
+ """
134
+ Convert self into a url
135
+
136
+ This function should more or less round-trip with :func:`.parse_url`. The
137
+ returned url may not be exactly the same as the url inputted to
138
+ :func:`.parse_url`, but it should be equivalent by the RFC (e.g., urls
139
+ with a blank port will have : removed).
140
+
141
+ Example: ::
142
+
143
+ >>> U = parse_url('http://google.com/mail/')
144
+ >>> U.url
145
+ 'http://google.com/mail/'
146
+ >>> Url('http', 'username:password', 'host.com', 80,
147
+ ... '/path', 'query', 'fragment').url
148
+ 'http://username:password@host.com:80/path?query#fragment'
149
+ """
150
+ scheme, auth, host, port, path, query, fragment = self
151
+ url = u""
152
+
153
+ # We use "is not None" we want things to happen with empty strings (or 0 port)
154
+ if scheme is not None:
155
+ url += scheme + u"://"
156
+ if auth is not None:
157
+ url += auth + u"@"
158
+ if host is not None:
159
+ url += host
160
+ if port is not None:
161
+ url += u":" + str(port)
162
+ if path is not None:
163
+ url += path
164
+ if query is not None:
165
+ url += u"?" + query
166
+ if fragment is not None:
167
+ url += u"#" + fragment
168
+
169
+ return url
170
+
171
+ def __str__(self):
172
+ return self.url
173
+
174
+
175
+ def split_first(s, delims):
176
+ """
177
+ .. deprecated:: 1.25
178
+
179
+ Given a string and an iterable of delimiters, split on the first found
180
+ delimiter. Return two split parts and the matched delimiter.
181
+
182
+ If not found, then the first part is the full input string.
183
+
184
+ Example::
185
+
186
+ >>> split_first('foo/bar?baz', '?/=')
187
+ ('foo', 'bar?baz', '/')
188
+ >>> split_first('foo/bar?baz', '123')
189
+ ('foo/bar?baz', '', None)
190
+
191
+ Scales linearly with number of delims. Not ideal for large number of delims.
192
+ """
193
+ min_idx = None
194
+ min_delim = None
195
+ for d in delims:
196
+ idx = s.find(d)
197
+ if idx < 0:
198
+ continue
199
+
200
+ if min_idx is None or idx < min_idx:
201
+ min_idx = idx
202
+ min_delim = d
203
+
204
+ if min_idx is None or min_idx < 0:
205
+ return s, "", None
206
+
207
+ return s[:min_idx], s[min_idx + 1 :], min_delim
208
+
209
+
210
+ def _encode_invalid_chars(component, allowed_chars, encoding="utf-8"):
211
+ """Percent-encodes a URI component without reapplying
212
+ onto an already percent-encoded component.
213
+ """
214
+ if component is None:
215
+ return component
216
+
217
+ component = six.ensure_text(component)
218
+
219
+ # Normalize existing percent-encoded bytes.
220
+ # Try to see if the component we're encoding is already percent-encoded
221
+ # so we can skip all '%' characters but still encode all others.
222
+ component, percent_encodings = PERCENT_RE.subn(
223
+ lambda match: match.group(0).upper(), component
224
+ )
225
+
226
+ uri_bytes = component.encode("utf-8", "surrogatepass")
227
+ is_percent_encoded = percent_encodings == uri_bytes.count(b"%")
228
+ encoded_component = bytearray()
229
+
230
+ for i in range(0, len(uri_bytes)):
231
+ # Will return a single character bytestring on both Python 2 & 3
232
+ byte = uri_bytes[i : i + 1]
233
+ byte_ord = ord(byte)
234
+ if (is_percent_encoded and byte == b"%") or (
235
+ byte_ord < 128 and byte.decode() in allowed_chars
236
+ ):
237
+ encoded_component += byte
238
+ continue
239
+ encoded_component.extend(b"%" + (hex(byte_ord)[2:].encode().zfill(2).upper()))
240
+
241
+ return encoded_component.decode(encoding)
242
+
243
+
244
+ def _remove_path_dot_segments(path):
245
+ # See http://tools.ietf.org/html/rfc3986#section-5.2.4 for pseudo-code
246
+ segments = path.split("/") # Turn the path into a list of segments
247
+ output = [] # Initialize the variable to use to store output
248
+
249
+ for segment in segments:
250
+ # '.' is the current directory, so ignore it, it is superfluous
251
+ if segment == ".":
252
+ continue
253
+ # Anything other than '..', should be appended to the output
254
+ elif segment != "..":
255
+ output.append(segment)
256
+ # In this case segment == '..', if we can, we should pop the last
257
+ # element
258
+ elif output:
259
+ output.pop()
260
+
261
+ # If the path starts with '/' and the output is empty or the first string
262
+ # is non-empty
263
+ if path.startswith("/") and (not output or output[0]):
264
+ output.insert(0, "")
265
+
266
+ # If the path starts with '/.' or '/..' ensure we add one more empty
267
+ # string to add a trailing '/'
268
+ if path.endswith(("/.", "/..")):
269
+ output.append("")
270
+
271
+ return "/".join(output)
272
+
273
+
274
+ def _normalize_host(host, scheme):
275
+ if host:
276
+ if isinstance(host, six.binary_type):
277
+ host = six.ensure_str(host)
278
+
279
+ if scheme in NORMALIZABLE_SCHEMES:
280
+ is_ipv6 = IPV6_ADDRZ_RE.match(host)
281
+ if is_ipv6:
282
+ # IPv6 hosts of the form 'a::b%zone' are encoded in a URL as
283
+ # such per RFC 6874: 'a::b%25zone'. Unquote the ZoneID
284
+ # separator as necessary to return a valid RFC 4007 scoped IP.
285
+ match = ZONE_ID_RE.search(host)
286
+ if match:
287
+ start, end = match.span(1)
288
+ zone_id = host[start:end]
289
+
290
+ if zone_id.startswith("%25") and zone_id != "%25":
291
+ zone_id = zone_id[3:]
292
+ else:
293
+ zone_id = zone_id[1:]
294
+ zone_id = "%" + _encode_invalid_chars(zone_id, UNRESERVED_CHARS)
295
+ return host[:start].lower() + zone_id + host[end:]
296
+ else:
297
+ return host.lower()
298
+ elif not IPV4_RE.match(host):
299
+ return six.ensure_str(
300
+ b".".join([_idna_encode(label) for label in host.split(".")])
301
+ )
302
+ return host
303
+
304
+
305
+ def _idna_encode(name):
306
+ if name and any(ord(x) >= 128 for x in name):
307
+ try:
308
+ from pip._vendor import idna
309
+ except ImportError:
310
+ six.raise_from(
311
+ LocationParseError("Unable to parse URL without the 'idna' module"),
312
+ None,
313
+ )
314
+ try:
315
+ return idna.encode(name.lower(), strict=True, std3_rules=True)
316
+ except idna.IDNAError:
317
+ six.raise_from(
318
+ LocationParseError(u"Name '%s' is not a valid IDNA label" % name), None
319
+ )
320
+ return name.lower().encode("ascii")
321
+
322
+
323
+ def _encode_target(target):
324
+ """Percent-encodes a request target so that there are no invalid characters"""
325
+ path, query = TARGET_RE.match(target).groups()
326
+ target = _encode_invalid_chars(path, PATH_CHARS)
327
+ query = _encode_invalid_chars(query, QUERY_CHARS)
328
+ if query is not None:
329
+ target += "?" + query
330
+ return target
331
+
332
+
333
+ def parse_url(url):
334
+ """
335
+ Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
336
+ performed to parse incomplete urls. Fields not provided will be None.
337
+ This parser is RFC 3986 and RFC 6874 compliant.
338
+
339
+ The parser logic and helper functions are based heavily on
340
+ work done in the ``rfc3986`` module.
341
+
342
+ :param str url: URL to parse into a :class:`.Url` namedtuple.
343
+
344
+ Partly backwards-compatible with :mod:`urlparse`.
345
+
346
+ Example::
347
+
348
+ >>> parse_url('http://google.com/mail/')
349
+ Url(scheme='http', host='google.com', port=None, path='/mail/', ...)
350
+ >>> parse_url('google.com:80')
351
+ Url(scheme=None, host='google.com', port=80, path=None, ...)
352
+ >>> parse_url('/foo?bar')
353
+ Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
354
+ """
355
+ if not url:
356
+ # Empty
357
+ return Url()
358
+
359
+ source_url = url
360
+ if not SCHEME_RE.search(url):
361
+ url = "//" + url
362
+
363
+ try:
364
+ scheme, authority, path, query, fragment = URI_RE.match(url).groups()
365
+ normalize_uri = scheme is None or scheme.lower() in NORMALIZABLE_SCHEMES
366
+
367
+ if scheme:
368
+ scheme = scheme.lower()
369
+
370
+ if authority:
371
+ auth, _, host_port = authority.rpartition("@")
372
+ auth = auth or None
373
+ host, port = _HOST_PORT_RE.match(host_port).groups()
374
+ if auth and normalize_uri:
375
+ auth = _encode_invalid_chars(auth, USERINFO_CHARS)
376
+ if port == "":
377
+ port = None
378
+ else:
379
+ auth, host, port = None, None, None
380
+
381
+ if port is not None:
382
+ port = int(port)
383
+ if not (0 <= port <= 65535):
384
+ raise LocationParseError(url)
385
+
386
+ host = _normalize_host(host, scheme)
387
+
388
+ if normalize_uri and path:
389
+ path = _remove_path_dot_segments(path)
390
+ path = _encode_invalid_chars(path, PATH_CHARS)
391
+ if normalize_uri and query:
392
+ query = _encode_invalid_chars(query, QUERY_CHARS)
393
+ if normalize_uri and fragment:
394
+ fragment = _encode_invalid_chars(fragment, FRAGMENT_CHARS)
395
+
396
+ except (ValueError, AttributeError):
397
+ return six.raise_from(LocationParseError(source_url), None)
398
+
399
+ # For the sake of backwards compatibility we put empty
400
+ # string values for path if there are any defined values
401
+ # beyond the path in the URL.
402
+ # TODO: Remove this when we break backwards compatibility.
403
+ if not path:
404
+ if query is not None or fragment is not None:
405
+ path = ""
406
+ else:
407
+ path = None
408
+
409
+ # Ensure that each part of the URL is a `str` for
410
+ # backwards compatibility.
411
+ if isinstance(url, six.text_type):
412
+ ensure_func = six.ensure_text
413
+ else:
414
+ ensure_func = six.ensure_str
415
+
416
+ def ensure_type(x):
417
+ return x if x is None else ensure_func(x)
418
+
419
+ return Url(
420
+ scheme=ensure_type(scheme),
421
+ auth=ensure_type(auth),
422
+ host=ensure_type(host),
423
+ port=port,
424
+ path=ensure_type(path),
425
+ query=ensure_type(query),
426
+ fragment=ensure_type(fragment),
427
+ )
428
+
429
+
430
+ def get_host(url):
431
+ """
432
+ Deprecated. Use :func:`parse_url` instead.
433
+ """
434
+ p = parse_url(url)
435
+ return p.scheme or "http", p.hostname, p.port
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pybind11/_version.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+
4
+ def _to_int(s: str) -> int | str:
5
+ try:
6
+ return int(s)
7
+ except ValueError:
8
+ return s
9
+
10
+
11
+ __version__ = "2.13.6"
12
+ version_info = tuple(_to_int(s) for s in __version__.split("."))
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pybind11/include/pybind11/attr.h ADDED
@@ -0,0 +1,690 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/attr.h: Infrastructure for processing custom
3
+ type and function attributes
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "detail/common.h"
14
+ #include "cast.h"
15
+
16
+ #include <functional>
17
+
18
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19
+
20
+ /// \addtogroup annotations
21
+ /// @{
22
+
23
+ /// Annotation for methods
24
+ struct is_method {
25
+ handle class_;
26
+ explicit is_method(const handle &c) : class_(c) {}
27
+ };
28
+
29
+ /// Annotation for setters
30
+ struct is_setter {};
31
+
32
+ /// Annotation for operators
33
+ struct is_operator {};
34
+
35
+ /// Annotation for classes that cannot be subclassed
36
+ struct is_final {};
37
+
38
+ /// Annotation for parent scope
39
+ struct scope {
40
+ handle value;
41
+ explicit scope(const handle &s) : value(s) {}
42
+ };
43
+
44
+ /// Annotation for documentation
45
+ struct doc {
46
+ const char *value;
47
+ explicit doc(const char *value) : value(value) {}
48
+ };
49
+
50
+ /// Annotation for function names
51
+ struct name {
52
+ const char *value;
53
+ explicit name(const char *value) : value(value) {}
54
+ };
55
+
56
+ /// Annotation indicating that a function is an overload associated with a given "sibling"
57
+ struct sibling {
58
+ handle value;
59
+ explicit sibling(const handle &value) : value(value.ptr()) {}
60
+ };
61
+
62
+ /// Annotation indicating that a class derives from another given type
63
+ template <typename T>
64
+ struct base {
65
+
66
+ PYBIND11_DEPRECATED(
67
+ "base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
68
+ base() = default;
69
+ };
70
+
71
+ /// Keep patient alive while nurse lives
72
+ template <size_t Nurse, size_t Patient>
73
+ struct keep_alive {};
74
+
75
+ /// Annotation indicating that a class is involved in a multiple inheritance relationship
76
+ struct multiple_inheritance {};
77
+
78
+ /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
79
+ struct dynamic_attr {};
80
+
81
+ /// Annotation which enables the buffer protocol for a type
82
+ struct buffer_protocol {};
83
+
84
+ /// Annotation which requests that a special metaclass is created for a type
85
+ struct metaclass {
86
+ handle value;
87
+
88
+ PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
89
+ metaclass() = default;
90
+
91
+ /// Override pybind11's default metaclass
92
+ explicit metaclass(handle value) : value(value) {}
93
+ };
94
+
95
+ /// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that
96
+ /// may be used to customize the Python type.
97
+ ///
98
+ /// The callback is invoked immediately before `PyType_Ready`.
99
+ ///
100
+ /// Note: This is an advanced interface, and uses of it may require changes to
101
+ /// work with later versions of pybind11. You may wish to consult the
102
+ /// implementation of `make_new_python_type` in `detail/classes.h` to understand
103
+ /// the context in which the callback will be run.
104
+ struct custom_type_setup {
105
+ using callback = std::function<void(PyHeapTypeObject *heap_type)>;
106
+
107
+ explicit custom_type_setup(callback value) : value(std::move(value)) {}
108
+
109
+ callback value;
110
+ };
111
+
112
+ /// Annotation that marks a class as local to the module:
113
+ struct module_local {
114
+ const bool value;
115
+ constexpr explicit module_local(bool v = true) : value(v) {}
116
+ };
117
+
118
+ /// Annotation to mark enums as an arithmetic type
119
+ struct arithmetic {};
120
+
121
+ /// Mark a function for addition at the beginning of the existing overload chain instead of the end
122
+ struct prepend {};
123
+
124
+ /** \rst
125
+ A call policy which places one or more guard variables (``Ts...``) around the function call.
126
+
127
+ For example, this definition:
128
+
129
+ .. code-block:: cpp
130
+
131
+ m.def("foo", foo, py::call_guard<T>());
132
+
133
+ is equivalent to the following pseudocode:
134
+
135
+ .. code-block:: cpp
136
+
137
+ m.def("foo", [](args...) {
138
+ T scope_guard;
139
+ return foo(args...); // forwarded arguments
140
+ });
141
+ \endrst */
142
+ template <typename... Ts>
143
+ struct call_guard;
144
+
145
+ template <>
146
+ struct call_guard<> {
147
+ using type = detail::void_type;
148
+ };
149
+
150
+ template <typename T>
151
+ struct call_guard<T> {
152
+ static_assert(std::is_default_constructible<T>::value,
153
+ "The guard type must be default constructible");
154
+
155
+ using type = T;
156
+ };
157
+
158
+ template <typename T, typename... Ts>
159
+ struct call_guard<T, Ts...> {
160
+ struct type {
161
+ T guard{}; // Compose multiple guard types with left-to-right default-constructor order
162
+ typename call_guard<Ts...>::type next{};
163
+ };
164
+ };
165
+
166
+ /// @} annotations
167
+
168
+ PYBIND11_NAMESPACE_BEGIN(detail)
169
+ /* Forward declarations */
170
+ enum op_id : int;
171
+ enum op_type : int;
172
+ struct undefined_t;
173
+ template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t>
174
+ struct op_;
175
+ void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
176
+
177
+ /// Internal data structure which holds metadata about a keyword argument
178
+ struct argument_record {
179
+ const char *name; ///< Argument name
180
+ const char *descr; ///< Human-readable version of the argument value
181
+ handle value; ///< Associated Python object
182
+ bool convert : 1; ///< True if the argument is allowed to convert when loading
183
+ bool none : 1; ///< True if None is allowed when loading
184
+
185
+ argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
186
+ : name(name), descr(descr), value(value), convert(convert), none(none) {}
187
+ };
188
+
189
+ /// Internal data structure which holds metadata about a bound function (signature, overloads,
190
+ /// etc.)
191
+ struct function_record {
192
+ function_record()
193
+ : is_constructor(false), is_new_style_constructor(false), is_stateless(false),
194
+ is_operator(false), is_method(false), is_setter(false), has_args(false),
195
+ has_kwargs(false), prepend(false) {}
196
+
197
+ /// Function name
198
+ char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
199
+
200
+ // User-specified documentation string
201
+ char *doc = nullptr;
202
+
203
+ /// Human-readable version of the function signature
204
+ char *signature = nullptr;
205
+
206
+ /// List of registered keyword arguments
207
+ std::vector<argument_record> args;
208
+
209
+ /// Pointer to lambda function which converts arguments and performs the actual call
210
+ handle (*impl)(function_call &) = nullptr;
211
+
212
+ /// Storage for the wrapped function pointer and captured data, if any
213
+ void *data[3] = {};
214
+
215
+ /// Pointer to custom destructor for 'data' (if needed)
216
+ void (*free_data)(function_record *ptr) = nullptr;
217
+
218
+ /// Return value policy associated with this function
219
+ return_value_policy policy = return_value_policy::automatic;
220
+
221
+ /// True if name == '__init__'
222
+ bool is_constructor : 1;
223
+
224
+ /// True if this is a new-style `__init__` defined in `detail/init.h`
225
+ bool is_new_style_constructor : 1;
226
+
227
+ /// True if this is a stateless function pointer
228
+ bool is_stateless : 1;
229
+
230
+ /// True if this is an operator (__add__), etc.
231
+ bool is_operator : 1;
232
+
233
+ /// True if this is a method
234
+ bool is_method : 1;
235
+
236
+ /// True if this is a setter
237
+ bool is_setter : 1;
238
+
239
+ /// True if the function has a '*args' argument
240
+ bool has_args : 1;
241
+
242
+ /// True if the function has a '**kwargs' argument
243
+ bool has_kwargs : 1;
244
+
245
+ /// True if this function is to be inserted at the beginning of the overload resolution chain
246
+ bool prepend : 1;
247
+
248
+ /// Number of arguments (including py::args and/or py::kwargs, if present)
249
+ std::uint16_t nargs;
250
+
251
+ /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs
252
+ /// argument or by a py::kw_only annotation.
253
+ std::uint16_t nargs_pos = 0;
254
+
255
+ /// Number of leading arguments (counted in `nargs`) that are positional-only
256
+ std::uint16_t nargs_pos_only = 0;
257
+
258
+ /// Python method object
259
+ PyMethodDef *def = nullptr;
260
+
261
+ /// Python handle to the parent scope (a class or a module)
262
+ handle scope;
263
+
264
+ /// Python handle to the sibling function representing an overload chain
265
+ handle sibling;
266
+
267
+ /// Pointer to next overload
268
+ function_record *next = nullptr;
269
+ };
270
+
271
+ /// Special data structure which (temporarily) holds metadata about a bound class
272
+ struct type_record {
273
+ PYBIND11_NOINLINE type_record()
274
+ : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),
275
+ default_holder(true), module_local(false), is_final(false) {}
276
+
277
+ /// Handle to the parent scope
278
+ handle scope;
279
+
280
+ /// Name of the class
281
+ const char *name = nullptr;
282
+
283
+ // Pointer to RTTI type_info data structure
284
+ const std::type_info *type = nullptr;
285
+
286
+ /// How large is the underlying C++ type?
287
+ size_t type_size = 0;
288
+
289
+ /// What is the alignment of the underlying C++ type?
290
+ size_t type_align = 0;
291
+
292
+ /// How large is the type's holder?
293
+ size_t holder_size = 0;
294
+
295
+ /// The global operator new can be overridden with a class-specific variant
296
+ void *(*operator_new)(size_t) = nullptr;
297
+
298
+ /// Function pointer to class_<..>::init_instance
299
+ void (*init_instance)(instance *, const void *) = nullptr;
300
+
301
+ /// Function pointer to class_<..>::dealloc
302
+ void (*dealloc)(detail::value_and_holder &) = nullptr;
303
+
304
+ /// List of base classes of the newly created type
305
+ list bases;
306
+
307
+ /// Optional docstring
308
+ const char *doc = nullptr;
309
+
310
+ /// Custom metaclass (optional)
311
+ handle metaclass;
312
+
313
+ /// Custom type setup.
314
+ custom_type_setup::callback custom_type_setup_callback;
315
+
316
+ /// Multiple inheritance marker
317
+ bool multiple_inheritance : 1;
318
+
319
+ /// Does the class manage a __dict__?
320
+ bool dynamic_attr : 1;
321
+
322
+ /// Does the class implement the buffer protocol?
323
+ bool buffer_protocol : 1;
324
+
325
+ /// Is the default (unique_ptr) holder type used?
326
+ bool default_holder : 1;
327
+
328
+ /// Is the class definition local to the module shared object?
329
+ bool module_local : 1;
330
+
331
+ /// Is the class inheritable from python classes?
332
+ bool is_final : 1;
333
+
334
+ PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) {
335
+ auto *base_info = detail::get_type_info(base, false);
336
+ if (!base_info) {
337
+ std::string tname(base.name());
338
+ detail::clean_type_id(tname);
339
+ pybind11_fail("generic_type: type \"" + std::string(name)
340
+ + "\" referenced unknown base type \"" + tname + "\"");
341
+ }
342
+
343
+ if (default_holder != base_info->default_holder) {
344
+ std::string tname(base.name());
345
+ detail::clean_type_id(tname);
346
+ pybind11_fail("generic_type: type \"" + std::string(name) + "\" "
347
+ + (default_holder ? "does not have" : "has")
348
+ + " a non-default holder type while its base \"" + tname + "\" "
349
+ + (base_info->default_holder ? "does not" : "does"));
350
+ }
351
+
352
+ bases.append((PyObject *) base_info->type);
353
+
354
+ #if PY_VERSION_HEX < 0x030B0000
355
+ dynamic_attr |= base_info->type->tp_dictoffset != 0;
356
+ #else
357
+ dynamic_attr |= (base_info->type->tp_flags & Py_TPFLAGS_MANAGED_DICT) != 0;
358
+ #endif
359
+
360
+ if (caster) {
361
+ base_info->implicit_casts.emplace_back(type, caster);
362
+ }
363
+ }
364
+ };
365
+
366
+ inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) {
367
+ args.reserve(f.nargs);
368
+ args_convert.reserve(f.nargs);
369
+ }
370
+
371
+ /// Tag for a new-style `__init__` defined in `detail/init.h`
372
+ struct is_new_style_constructor {};
373
+
374
+ /**
375
+ * Partial template specializations to process custom attributes provided to
376
+ * cpp_function_ and class_. These are either used to initialize the respective
377
+ * fields in the type_record and function_record data structures or executed at
378
+ * runtime to deal with custom call policies (e.g. keep_alive).
379
+ */
380
+ template <typename T, typename SFINAE = void>
381
+ struct process_attribute;
382
+
383
+ template <typename T>
384
+ struct process_attribute_default {
385
+ /// Default implementation: do nothing
386
+ static void init(const T &, function_record *) {}
387
+ static void init(const T &, type_record *) {}
388
+ static void precall(function_call &) {}
389
+ static void postcall(function_call &, handle) {}
390
+ };
391
+
392
+ /// Process an attribute specifying the function's name
393
+ template <>
394
+ struct process_attribute<name> : process_attribute_default<name> {
395
+ static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
396
+ };
397
+
398
+ /// Process an attribute specifying the function's docstring
399
+ template <>
400
+ struct process_attribute<doc> : process_attribute_default<doc> {
401
+ static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
402
+ };
403
+
404
+ /// Process an attribute specifying the function's docstring (provided as a C-style string)
405
+ template <>
406
+ struct process_attribute<const char *> : process_attribute_default<const char *> {
407
+ static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
408
+ static void init(const char *d, type_record *r) { r->doc = d; }
409
+ };
410
+ template <>
411
+ struct process_attribute<char *> : process_attribute<const char *> {};
412
+
413
+ /// Process an attribute indicating the function's return value policy
414
+ template <>
415
+ struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
416
+ static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
417
+ };
418
+
419
+ /// Process an attribute which indicates that this is an overloaded function associated with a
420
+ /// given sibling
421
+ template <>
422
+ struct process_attribute<sibling> : process_attribute_default<sibling> {
423
+ static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
424
+ };
425
+
426
+ /// Process an attribute which indicates that this function is a method
427
+ template <>
428
+ struct process_attribute<is_method> : process_attribute_default<is_method> {
429
+ static void init(const is_method &s, function_record *r) {
430
+ r->is_method = true;
431
+ r->scope = s.class_;
432
+ }
433
+ };
434
+
435
+ /// Process an attribute which indicates that this function is a setter
436
+ template <>
437
+ struct process_attribute<is_setter> : process_attribute_default<is_setter> {
438
+ static void init(const is_setter &, function_record *r) { r->is_setter = true; }
439
+ };
440
+
441
+ /// Process an attribute which indicates the parent scope of a method
442
+ template <>
443
+ struct process_attribute<scope> : process_attribute_default<scope> {
444
+ static void init(const scope &s, function_record *r) { r->scope = s.value; }
445
+ };
446
+
447
+ /// Process an attribute which indicates that this function is an operator
448
+ template <>
449
+ struct process_attribute<is_operator> : process_attribute_default<is_operator> {
450
+ static void init(const is_operator &, function_record *r) { r->is_operator = true; }
451
+ };
452
+
453
+ template <>
454
+ struct process_attribute<is_new_style_constructor>
455
+ : process_attribute_default<is_new_style_constructor> {
456
+ static void init(const is_new_style_constructor &, function_record *r) {
457
+ r->is_new_style_constructor = true;
458
+ }
459
+ };
460
+
461
+ inline void check_kw_only_arg(const arg &a, function_record *r) {
462
+ if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) {
463
+ pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or "
464
+ "args() argument");
465
+ }
466
+ }
467
+
468
+ inline void append_self_arg_if_needed(function_record *r) {
469
+ if (r->is_method && r->args.empty()) {
470
+ r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false);
471
+ }
472
+ }
473
+
474
+ /// Process a keyword argument attribute (*without* a default value)
475
+ template <>
476
+ struct process_attribute<arg> : process_attribute_default<arg> {
477
+ static void init(const arg &a, function_record *r) {
478
+ append_self_arg_if_needed(r);
479
+ r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
480
+
481
+ check_kw_only_arg(a, r);
482
+ }
483
+ };
484
+
485
+ /// Process a keyword argument attribute (*with* a default value)
486
+ template <>
487
+ struct process_attribute<arg_v> : process_attribute_default<arg_v> {
488
+ static void init(const arg_v &a, function_record *r) {
489
+ if (r->is_method && r->args.empty()) {
490
+ r->args.emplace_back(
491
+ "self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false);
492
+ }
493
+
494
+ if (!a.value) {
495
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
496
+ std::string descr("'");
497
+ if (a.name) {
498
+ descr += std::string(a.name) + ": ";
499
+ }
500
+ descr += a.type + "'";
501
+ if (r->is_method) {
502
+ if (r->name) {
503
+ descr += " in method '" + (std::string) str(r->scope) + "."
504
+ + (std::string) r->name + "'";
505
+ } else {
506
+ descr += " in method of '" + (std::string) str(r->scope) + "'";
507
+ }
508
+ } else if (r->name) {
509
+ descr += " in function '" + (std::string) r->name + "'";
510
+ }
511
+ pybind11_fail("arg(): could not convert default argument " + descr
512
+ + " into a Python object (type not registered yet?)");
513
+ #else
514
+ pybind11_fail("arg(): could not convert default argument "
515
+ "into a Python object (type not registered yet?). "
516
+ "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
517
+ "more information.");
518
+ #endif
519
+ }
520
+ r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
521
+
522
+ check_kw_only_arg(a, r);
523
+ }
524
+ };
525
+
526
+ /// Process a keyword-only-arguments-follow pseudo argument
527
+ template <>
528
+ struct process_attribute<kw_only> : process_attribute_default<kw_only> {
529
+ static void init(const kw_only &, function_record *r) {
530
+ append_self_arg_if_needed(r);
531
+ if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) {
532
+ pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative "
533
+ "argument location (or omit kw_only() entirely)");
534
+ }
535
+ r->nargs_pos = static_cast<std::uint16_t>(r->args.size());
536
+ }
537
+ };
538
+
539
+ /// Process a positional-only-argument maker
540
+ template <>
541
+ struct process_attribute<pos_only> : process_attribute_default<pos_only> {
542
+ static void init(const pos_only &, function_record *r) {
543
+ append_self_arg_if_needed(r);
544
+ r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
545
+ if (r->nargs_pos_only > r->nargs_pos) {
546
+ pybind11_fail("pos_only(): cannot follow a py::args() argument");
547
+ }
548
+ // It also can't follow a kw_only, but a static_assert in pybind11.h checks that
549
+ }
550
+ };
551
+
552
+ /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees
553
+ /// that)
554
+ template <typename T>
555
+ struct process_attribute<T, enable_if_t<is_pyobject<T>::value>>
556
+ : process_attribute_default<handle> {
557
+ static void init(const handle &h, type_record *r) { r->bases.append(h); }
558
+ };
559
+
560
+ /// Process a parent class attribute (deprecated, does not support multiple inheritance)
561
+ template <typename T>
562
+ struct process_attribute<base<T>> : process_attribute_default<base<T>> {
563
+ static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
564
+ };
565
+
566
+ /// Process a multiple inheritance attribute
567
+ template <>
568
+ struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
569
+ static void init(const multiple_inheritance &, type_record *r) {
570
+ r->multiple_inheritance = true;
571
+ }
572
+ };
573
+
574
+ template <>
575
+ struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
576
+ static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
577
+ };
578
+
579
+ template <>
580
+ struct process_attribute<custom_type_setup> {
581
+ static void init(const custom_type_setup &value, type_record *r) {
582
+ r->custom_type_setup_callback = value.value;
583
+ }
584
+ };
585
+
586
+ template <>
587
+ struct process_attribute<is_final> : process_attribute_default<is_final> {
588
+ static void init(const is_final &, type_record *r) { r->is_final = true; }
589
+ };
590
+
591
+ template <>
592
+ struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
593
+ static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
594
+ };
595
+
596
+ template <>
597
+ struct process_attribute<metaclass> : process_attribute_default<metaclass> {
598
+ static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
599
+ };
600
+
601
+ template <>
602
+ struct process_attribute<module_local> : process_attribute_default<module_local> {
603
+ static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
604
+ };
605
+
606
+ /// Process a 'prepend' attribute, putting this at the beginning of the overload chain
607
+ template <>
608
+ struct process_attribute<prepend> : process_attribute_default<prepend> {
609
+ static void init(const prepend &, function_record *r) { r->prepend = true; }
610
+ };
611
+
612
+ /// Process an 'arithmetic' attribute for enums (does nothing here)
613
+ template <>
614
+ struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
615
+
616
+ template <typename... Ts>
617
+ struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {};
618
+
619
+ /**
620
+ * Process a keep_alive call policy -- invokes keep_alive_impl during the
621
+ * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
622
+ * otherwise
623
+ */
624
+ template <size_t Nurse, size_t Patient>
625
+ struct process_attribute<keep_alive<Nurse, Patient>>
626
+ : public process_attribute_default<keep_alive<Nurse, Patient>> {
627
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
628
+ static void precall(function_call &call) {
629
+ keep_alive_impl(Nurse, Patient, call, handle());
630
+ }
631
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
632
+ static void postcall(function_call &, handle) {}
633
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
634
+ static void precall(function_call &) {}
635
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
636
+ static void postcall(function_call &call, handle ret) {
637
+ keep_alive_impl(Nurse, Patient, call, ret);
638
+ }
639
+ };
640
+
641
+ /// Recursively iterate over variadic template arguments
642
+ template <typename... Args>
643
+ struct process_attributes {
644
+ static void init(const Args &...args, function_record *r) {
645
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
646
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
647
+ using expander = int[];
648
+ (void) expander{
649
+ 0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
650
+ }
651
+ static void init(const Args &...args, type_record *r) {
652
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
653
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
654
+ using expander = int[];
655
+ (void) expander{0,
656
+ (process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
657
+ }
658
+ static void precall(function_call &call) {
659
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call);
660
+ using expander = int[];
661
+ (void) expander{0,
662
+ (process_attribute<typename std::decay<Args>::type>::precall(call), 0)...};
663
+ }
664
+ static void postcall(function_call &call, handle fn_ret) {
665
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret);
666
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret);
667
+ using expander = int[];
668
+ (void) expander{
669
+ 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...};
670
+ }
671
+ };
672
+
673
+ template <typename T>
674
+ using is_call_guard = is_instantiation<call_guard, T>;
675
+
676
+ /// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
677
+ template <typename... Extra>
678
+ using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
679
+
680
+ /// Check the number of named arguments at compile time
681
+ template <typename... Extra,
682
+ size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
683
+ size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
684
+ constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
685
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);
686
+ return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs;
687
+ }
688
+
689
+ PYBIND11_NAMESPACE_END(detail)
690
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pybind11/include/pybind11/chrono.h ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime
3
+
4
+ Copyright (c) 2016 Trent Houliston <trent@houliston.me> and
5
+ Wenzel Jakob <wenzel.jakob@epfl.ch>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "pybind11.h"
14
+
15
+ #include <chrono>
16
+ #include <cmath>
17
+ #include <ctime>
18
+ #include <datetime.h>
19
+ #include <mutex>
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+ PYBIND11_NAMESPACE_BEGIN(detail)
23
+
24
+ template <typename type>
25
+ class duration_caster {
26
+ public:
27
+ using rep = typename type::rep;
28
+ using period = typename type::period;
29
+
30
+ // signed 25 bits required by the standard.
31
+ using days = std::chrono::duration<int_least32_t, std::ratio<86400>>;
32
+
33
+ bool load(handle src, bool) {
34
+ using namespace std::chrono;
35
+
36
+ // Lazy initialise the PyDateTime import
37
+ if (!PyDateTimeAPI) {
38
+ PyDateTime_IMPORT;
39
+ }
40
+
41
+ if (!src) {
42
+ return false;
43
+ }
44
+ // If invoked with datetime.delta object
45
+ if (PyDelta_Check(src.ptr())) {
46
+ value = type(duration_cast<duration<rep, period>>(
47
+ days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
48
+ + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
49
+ + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
50
+ return true;
51
+ }
52
+ // If invoked with a float we assume it is seconds and convert
53
+ if (PyFloat_Check(src.ptr())) {
54
+ value = type(duration_cast<duration<rep, period>>(
55
+ duration<double>(PyFloat_AsDouble(src.ptr()))));
56
+ return true;
57
+ }
58
+ return false;
59
+ }
60
+
61
+ // If this is a duration just return it back
62
+ static const std::chrono::duration<rep, period> &
63
+ get_duration(const std::chrono::duration<rep, period> &src) {
64
+ return src;
65
+ }
66
+
67
+ // If this is a time_point get the time_since_epoch
68
+ template <typename Clock>
69
+ static std::chrono::duration<rep, period>
70
+ get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
71
+ return src.time_since_epoch();
72
+ }
73
+
74
+ static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
75
+ using namespace std::chrono;
76
+
77
+ // Use overloaded function to get our duration from our source
78
+ // Works out if it is a duration or time_point and get the duration
79
+ auto d = get_duration(src);
80
+
81
+ // Lazy initialise the PyDateTime import
82
+ if (!PyDateTimeAPI) {
83
+ PyDateTime_IMPORT;
84
+ }
85
+
86
+ // Declare these special duration types so the conversions happen with the correct
87
+ // primitive types (int)
88
+ using dd_t = duration<int, std::ratio<86400>>;
89
+ using ss_t = duration<int, std::ratio<1>>;
90
+ using us_t = duration<int, std::micro>;
91
+
92
+ auto dd = duration_cast<dd_t>(d);
93
+ auto subd = d - dd;
94
+ auto ss = duration_cast<ss_t>(subd);
95
+ auto us = duration_cast<us_t>(subd - ss);
96
+ return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
97
+ }
98
+
99
+ PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta"));
100
+ };
101
+
102
+ inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
103
+ #if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
104
+ if (localtime_s(buf, time))
105
+ return nullptr;
106
+ return buf;
107
+ #else
108
+ static std::mutex mtx;
109
+ std::lock_guard<std::mutex> lock(mtx);
110
+ std::tm *tm_ptr = std::localtime(time);
111
+ if (tm_ptr != nullptr) {
112
+ *buf = *tm_ptr;
113
+ }
114
+ return tm_ptr;
115
+ #endif
116
+ }
117
+
118
+ // This is for casting times on the system clock into datetime.datetime instances
119
+ template <typename Duration>
120
+ class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
121
+ public:
122
+ using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
123
+ bool load(handle src, bool) {
124
+ using namespace std::chrono;
125
+
126
+ // Lazy initialise the PyDateTime import
127
+ if (!PyDateTimeAPI) {
128
+ PyDateTime_IMPORT;
129
+ }
130
+
131
+ if (!src) {
132
+ return false;
133
+ }
134
+
135
+ std::tm cal;
136
+ microseconds msecs;
137
+
138
+ if (PyDateTime_Check(src.ptr())) {
139
+ cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
140
+ cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
141
+ cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
142
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
143
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
144
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
145
+ cal.tm_isdst = -1;
146
+ msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
147
+ } else if (PyDate_Check(src.ptr())) {
148
+ cal.tm_sec = 0;
149
+ cal.tm_min = 0;
150
+ cal.tm_hour = 0;
151
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
152
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
153
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
154
+ cal.tm_isdst = -1;
155
+ msecs = microseconds(0);
156
+ } else if (PyTime_Check(src.ptr())) {
157
+ cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
158
+ cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
159
+ cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
160
+ cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
161
+ cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
162
+ cal.tm_year = 70; // earliest available date for Python's datetime
163
+ cal.tm_isdst = -1;
164
+ msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
165
+ } else {
166
+ return false;
167
+ }
168
+
169
+ value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
170
+ return true;
171
+ }
172
+
173
+ static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,
174
+ return_value_policy /* policy */,
175
+ handle /* parent */) {
176
+ using namespace std::chrono;
177
+
178
+ // Lazy initialise the PyDateTime import
179
+ if (!PyDateTimeAPI) {
180
+ PyDateTime_IMPORT;
181
+ }
182
+
183
+ // Get out microseconds, and make sure they are positive, to avoid bug in eastern
184
+ // hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)
185
+ using us_t = duration<int, std::micro>;
186
+ auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
187
+ if (us.count() < 0) {
188
+ us += seconds(1);
189
+ }
190
+
191
+ // Subtract microseconds BEFORE `system_clock::to_time_t`, because:
192
+ // > If std::time_t has lower precision, it is implementation-defined whether the value is
193
+ // rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
194
+ std::time_t tt
195
+ = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
196
+
197
+ std::tm localtime;
198
+ std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
199
+ if (!localtime_ptr) {
200
+ throw cast_error("Unable to represent system_clock in local time");
201
+ }
202
+ return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
203
+ localtime.tm_mon + 1,
204
+ localtime.tm_mday,
205
+ localtime.tm_hour,
206
+ localtime.tm_min,
207
+ localtime.tm_sec,
208
+ us.count());
209
+ }
210
+ PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime"));
211
+ };
212
+
213
+ // Other clocks that are not the system clock are not measured as datetime.datetime objects
214
+ // since they are not measured on calendar time. So instead we just make them timedeltas
215
+ // Or if they have passed us a time as a float we convert that
216
+ template <typename Clock, typename Duration>
217
+ class type_caster<std::chrono::time_point<Clock, Duration>>
218
+ : public duration_caster<std::chrono::time_point<Clock, Duration>> {};
219
+
220
+ template <typename Rep, typename Period>
221
+ class type_caster<std::chrono::duration<Rep, Period>>
222
+ : public duration_caster<std::chrono::duration<Rep, Period>> {};
223
+
224
+ PYBIND11_NAMESPACE_END(detail)
225
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pybind11/include/pybind11/eval.h ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/eval.h: Support for evaluating Python expressions and statements
3
+ from strings and files
4
+
5
+ Copyright (c) 2016 Klemens Morgenstern <klemens.morgenstern@ed-chemnitz.de> and
6
+ Wenzel Jakob <wenzel.jakob@epfl.ch>
7
+
8
+ All rights reserved. Use of this source code is governed by a
9
+ BSD-style license that can be found in the LICENSE file.
10
+ */
11
+
12
+ #pragma once
13
+
14
+ #include "pybind11.h"
15
+
16
+ #include <utility>
17
+
18
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19
+ PYBIND11_NAMESPACE_BEGIN(detail)
20
+
21
+ inline void ensure_builtins_in_globals(object &global) {
22
+ #if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x03080000
23
+ // Running exec and eval adds `builtins` module under `__builtins__` key to
24
+ // globals if not yet present. Python 3.8 made PyRun_String behave
25
+ // similarly. Let's also do that for older versions, for consistency. This
26
+ // was missing from PyPy3.8 7.3.7.
27
+ if (!global.contains("__builtins__"))
28
+ global["__builtins__"] = module_::import(PYBIND11_BUILTINS_MODULE);
29
+ #else
30
+ (void) global;
31
+ #endif
32
+ }
33
+
34
+ PYBIND11_NAMESPACE_END(detail)
35
+
36
+ enum eval_mode {
37
+ /// Evaluate a string containing an isolated expression
38
+ eval_expr,
39
+
40
+ /// Evaluate a string containing a single statement. Returns \c none
41
+ eval_single_statement,
42
+
43
+ /// Evaluate a string containing a sequence of statement. Returns \c none
44
+ eval_statements
45
+ };
46
+
47
+ template <eval_mode mode = eval_expr>
48
+ object eval(const str &expr, object global = globals(), object local = object()) {
49
+ if (!local) {
50
+ local = global;
51
+ }
52
+
53
+ detail::ensure_builtins_in_globals(global);
54
+
55
+ /* PyRun_String does not accept a PyObject / encoding specifier,
56
+ this seems to be the only alternative */
57
+ std::string buffer = "# -*- coding: utf-8 -*-\n" + (std::string) expr;
58
+
59
+ int start = 0;
60
+ switch (mode) {
61
+ case eval_expr:
62
+ start = Py_eval_input;
63
+ break;
64
+ case eval_single_statement:
65
+ start = Py_single_input;
66
+ break;
67
+ case eval_statements:
68
+ start = Py_file_input;
69
+ break;
70
+ default:
71
+ pybind11_fail("invalid evaluation mode");
72
+ }
73
+
74
+ PyObject *result = PyRun_String(buffer.c_str(), start, global.ptr(), local.ptr());
75
+ if (!result) {
76
+ throw error_already_set();
77
+ }
78
+ return reinterpret_steal<object>(result);
79
+ }
80
+
81
+ template <eval_mode mode = eval_expr, size_t N>
82
+ object eval(const char (&s)[N], object global = globals(), object local = object()) {
83
+ /* Support raw string literals by removing common leading whitespace */
84
+ auto expr = (s[0] == '\n') ? str(module_::import("textwrap").attr("dedent")(s)) : str(s);
85
+ return eval<mode>(expr, std::move(global), std::move(local));
86
+ }
87
+
88
+ inline void exec(const str &expr, object global = globals(), object local = object()) {
89
+ eval<eval_statements>(expr, std::move(global), std::move(local));
90
+ }
91
+
92
+ template <size_t N>
93
+ void exec(const char (&s)[N], object global = globals(), object local = object()) {
94
+ eval<eval_statements>(s, std::move(global), std::move(local));
95
+ }
96
+
97
+ #if defined(PYPY_VERSION)
98
+ template <eval_mode mode = eval_statements>
99
+ object eval_file(str, object, object) {
100
+ pybind11_fail("eval_file not supported in PyPy3. Use eval");
101
+ }
102
+ template <eval_mode mode = eval_statements>
103
+ object eval_file(str, object) {
104
+ pybind11_fail("eval_file not supported in PyPy3. Use eval");
105
+ }
106
+ template <eval_mode mode = eval_statements>
107
+ object eval_file(str) {
108
+ pybind11_fail("eval_file not supported in PyPy3. Use eval");
109
+ }
110
+ #else
111
+ template <eval_mode mode = eval_statements>
112
+ object eval_file(str fname, object global = globals(), object local = object()) {
113
+ if (!local) {
114
+ local = global;
115
+ }
116
+
117
+ detail::ensure_builtins_in_globals(global);
118
+
119
+ int start = 0;
120
+ switch (mode) {
121
+ case eval_expr:
122
+ start = Py_eval_input;
123
+ break;
124
+ case eval_single_statement:
125
+ start = Py_single_input;
126
+ break;
127
+ case eval_statements:
128
+ start = Py_file_input;
129
+ break;
130
+ default:
131
+ pybind11_fail("invalid evaluation mode");
132
+ }
133
+
134
+ int closeFile = 1;
135
+ std::string fname_str = (std::string) fname;
136
+ FILE *f = _Py_fopen_obj(fname.ptr(), "r");
137
+ if (!f) {
138
+ PyErr_Clear();
139
+ pybind11_fail("File \"" + fname_str + "\" could not be opened!");
140
+ }
141
+
142
+ if (!global.contains("__file__")) {
143
+ global["__file__"] = std::move(fname);
144
+ }
145
+
146
+ PyObject *result
147
+ = PyRun_FileEx(f, fname_str.c_str(), start, global.ptr(), local.ptr(), closeFile);
148
+
149
+ if (!result) {
150
+ throw error_already_set();
151
+ }
152
+ return reinterpret_steal<object>(result);
153
+ }
154
+ #endif
155
+
156
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
tuning-competition-baseline/.venv/lib/python3.11/site-packages/pybind11/include/pybind11/operators.h ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/operator.h: Metatemplates for operator overloading
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+ PYBIND11_NAMESPACE_BEGIN(detail)
16
+
17
+ /// Enumeration with all supported operator types
18
+ enum op_id : int {
19
+ op_add,
20
+ op_sub,
21
+ op_mul,
22
+ op_div,
23
+ op_mod,
24
+ op_divmod,
25
+ op_pow,
26
+ op_lshift,
27
+ op_rshift,
28
+ op_and,
29
+ op_xor,
30
+ op_or,
31
+ op_neg,
32
+ op_pos,
33
+ op_abs,
34
+ op_invert,
35
+ op_int,
36
+ op_long,
37
+ op_float,
38
+ op_str,
39
+ op_cmp,
40
+ op_gt,
41
+ op_ge,
42
+ op_lt,
43
+ op_le,
44
+ op_eq,
45
+ op_ne,
46
+ op_iadd,
47
+ op_isub,
48
+ op_imul,
49
+ op_idiv,
50
+ op_imod,
51
+ op_ilshift,
52
+ op_irshift,
53
+ op_iand,
54
+ op_ixor,
55
+ op_ior,
56
+ op_complex,
57
+ op_bool,
58
+ op_nonzero,
59
+ op_repr,
60
+ op_truediv,
61
+ op_itruediv,
62
+ op_hash
63
+ };
64
+
65
+ enum op_type : int {
66
+ op_l, /* base type on left */
67
+ op_r, /* base type on right */
68
+ op_u /* unary operator */
69
+ };
70
+
71
+ struct self_t {};
72
+ static const self_t self = self_t();
73
+
74
+ /// Type for an unused type slot
75
+ struct undefined_t {};
76
+
77
+ /// Don't warn about an unused variable
78
+ inline self_t __self() { return self; }
79
+
80
+ /// base template of operator implementations
81
+ template <op_id, op_type, typename B, typename L, typename R>
82
+ struct op_impl {};
83
+
84
+ /// Operator implementation generator
85
+ template <op_id id, op_type ot, typename L, typename R>
86
+ struct op_ {
87
+ static constexpr bool op_enable_if_hook = true;
88
+ template <typename Class, typename... Extra>
89
+ void execute(Class &cl, const Extra &...extra) const {
90
+ using Base = typename Class::type;
91
+ using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;
92
+ using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;
93
+ using op = op_impl<id, ot, Base, L_type, R_type>;
94
+ cl.def(op::name(), &op::execute, is_operator(), extra...);
95
+ }
96
+ template <typename Class, typename... Extra>
97
+ void execute_cast(Class &cl, const Extra &...extra) const {
98
+ using Base = typename Class::type;
99
+ using L_type = conditional_t<std::is_same<L, self_t>::value, Base, L>;
100
+ using R_type = conditional_t<std::is_same<R, self_t>::value, Base, R>;
101
+ using op = op_impl<id, ot, Base, L_type, R_type>;
102
+ cl.def(op::name(), &op::execute_cast, is_operator(), extra...);
103
+ }
104
+ };
105
+
106
+ #define PYBIND11_BINARY_OPERATOR(id, rid, op, expr) \
107
+ template <typename B, typename L, typename R> \
108
+ struct op_impl<op_##id, op_l, B, L, R> { \
109
+ static char const *name() { return "__" #id "__"; } \
110
+ static auto execute(const L &l, const R &r) -> decltype(expr) { return (expr); } \
111
+ static B execute_cast(const L &l, const R &r) { return B(expr); } \
112
+ }; \
113
+ template <typename B, typename L, typename R> \
114
+ struct op_impl<op_##id, op_r, B, L, R> { \
115
+ static char const *name() { return "__" #rid "__"; } \
116
+ static auto execute(const R &r, const L &l) -> decltype(expr) { return (expr); } \
117
+ static B execute_cast(const R &r, const L &l) { return B(expr); } \
118
+ }; \
119
+ inline op_<op_##id, op_l, self_t, self_t> op(const self_t &, const self_t &) { \
120
+ return op_<op_##id, op_l, self_t, self_t>(); \
121
+ } \
122
+ template <typename T> \
123
+ op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
124
+ return op_<op_##id, op_l, self_t, T>(); \
125
+ } \
126
+ template <typename T> \
127
+ op_<op_##id, op_r, T, self_t> op(const T &, const self_t &) { \
128
+ return op_<op_##id, op_r, T, self_t>(); \
129
+ }
130
+
131
+ #define PYBIND11_INPLACE_OPERATOR(id, op, expr) \
132
+ template <typename B, typename L, typename R> \
133
+ struct op_impl<op_##id, op_l, B, L, R> { \
134
+ static char const *name() { return "__" #id "__"; } \
135
+ static auto execute(L &l, const R &r) -> decltype(expr) { return expr; } \
136
+ static B execute_cast(L &l, const R &r) { return B(expr); } \
137
+ }; \
138
+ template <typename T> \
139
+ op_<op_##id, op_l, self_t, T> op(const self_t &, const T &) { \
140
+ return op_<op_##id, op_l, self_t, T>(); \
141
+ }
142
+
143
+ #define PYBIND11_UNARY_OPERATOR(id, op, expr) \
144
+ template <typename B, typename L> \
145
+ struct op_impl<op_##id, op_u, B, L, undefined_t> { \
146
+ static char const *name() { return "__" #id "__"; } \
147
+ static auto execute(const L &l) -> decltype(expr) { return expr; } \
148
+ static B execute_cast(const L &l) { return B(expr); } \
149
+ }; \
150
+ inline op_<op_##id, op_u, self_t, undefined_t> op(const self_t &) { \
151
+ return op_<op_##id, op_u, self_t, undefined_t>(); \
152
+ }
153
+
154
+ PYBIND11_BINARY_OPERATOR(sub, rsub, operator-, l - r)
155
+ PYBIND11_BINARY_OPERATOR(add, radd, operator+, l + r)
156
+ PYBIND11_BINARY_OPERATOR(mul, rmul, operator*, l *r)
157
+ PYBIND11_BINARY_OPERATOR(truediv, rtruediv, operator/, l / r)
158
+ PYBIND11_BINARY_OPERATOR(mod, rmod, operator%, l % r)
159
+ PYBIND11_BINARY_OPERATOR(lshift, rlshift, operator<<, l << r)
160
+ PYBIND11_BINARY_OPERATOR(rshift, rrshift, operator>>, l >> r)
161
+ PYBIND11_BINARY_OPERATOR(and, rand, operator&, l &r)
162
+ PYBIND11_BINARY_OPERATOR(xor, rxor, operator^, l ^ r)
163
+ PYBIND11_BINARY_OPERATOR(eq, eq, operator==, l == r)
164
+ PYBIND11_BINARY_OPERATOR(ne, ne, operator!=, l != r)
165
+ PYBIND11_BINARY_OPERATOR(or, ror, operator|, l | r)
166
+ PYBIND11_BINARY_OPERATOR(gt, lt, operator>, l > r)
167
+ PYBIND11_BINARY_OPERATOR(ge, le, operator>=, l >= r)
168
+ PYBIND11_BINARY_OPERATOR(lt, gt, operator<, l < r)
169
+ PYBIND11_BINARY_OPERATOR(le, ge, operator<=, l <= r)
170
+ // PYBIND11_BINARY_OPERATOR(pow, rpow, pow, std::pow(l, r))
171
+ PYBIND11_INPLACE_OPERATOR(iadd, operator+=, l += r)
172
+ PYBIND11_INPLACE_OPERATOR(isub, operator-=, l -= r)
173
+ PYBIND11_INPLACE_OPERATOR(imul, operator*=, l *= r)
174
+ PYBIND11_INPLACE_OPERATOR(itruediv, operator/=, l /= r)
175
+ PYBIND11_INPLACE_OPERATOR(imod, operator%=, l %= r)
176
+ PYBIND11_INPLACE_OPERATOR(ilshift, operator<<=, l <<= r)
177
+ PYBIND11_INPLACE_OPERATOR(irshift, operator>>=, l >>= r)
178
+ PYBIND11_INPLACE_OPERATOR(iand, operator&=, l &= r)
179
+ PYBIND11_INPLACE_OPERATOR(ixor, operator^=, l ^= r)
180
+ PYBIND11_INPLACE_OPERATOR(ior, operator|=, l |= r)
181
+ PYBIND11_UNARY_OPERATOR(neg, operator-, -l)
182
+ PYBIND11_UNARY_OPERATOR(pos, operator+, +l)
183
+ // WARNING: This usage of `abs` should only be done for existing STL overloads.
184
+ // Adding overloads directly in to the `std::` namespace is advised against:
185
+ // https://en.cppreference.com/w/cpp/language/extending_std
186
+ PYBIND11_UNARY_OPERATOR(abs, abs, std::abs(l))
187
+ PYBIND11_UNARY_OPERATOR(hash, hash, std::hash<L>()(l))
188
+ PYBIND11_UNARY_OPERATOR(invert, operator~, (~l))
189
+ PYBIND11_UNARY_OPERATOR(bool, operator!, !!l)
190
+ PYBIND11_UNARY_OPERATOR(int, int_, (int) l)
191
+ PYBIND11_UNARY_OPERATOR(float, float_, (double) l)
192
+
193
+ #undef PYBIND11_BINARY_OPERATOR
194
+ #undef PYBIND11_INPLACE_OPERATOR
195
+ #undef PYBIND11_UNARY_OPERATOR
196
+ PYBIND11_NAMESPACE_END(detail)
197
+
198
+ using detail::self;
199
+ // Add named operators so that they are accessible via `py::`.
200
+ using detail::hash;
201
+
202
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)