├── .gitignore
├── COPYING
├── COPYING.LESSER
├── cl
├── AUTHORS
├── CL
│ ├── cl.h
│ ├── cl.hpp
│ ├── cl_d3d10.h
│ ├── cl_ext.h
│ ├── cl_gl.h
│ ├── cl_gl_ext.h
│ ├── cl_platform.h
│ └── opencl.h
├── buffer.go
├── commandQueue.go
├── context.go
├── device.go
├── image.go
├── kernel.go
├── memory.go
├── opencl.go
├── opencl_test.go
├── platform.go
├── program.go
├── sampler.go
├── vectAdd_test.go
└── vector.cl
├── examples
├── clinfo
│ └── clinfo.go
└── rotate
│ ├── rotate.cl
│ └── rotate.go
└── raw
├── LICENSE
├── README
├── byte_slice.go
├── byte_slice_test.go
├── reslice.go
├── reslice_test.go
├── runtime.go
├── runtime_test.go
├── type.go
└── type_test.go
/.gitignore:
--------------------------------------------------------------------------------
1 | clinfo/clinfo
2 | cl/demo/rotate/rotate
3 |
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/COPYING.LESSER:
--------------------------------------------------------------------------------
1 | GNU LESSER GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
--------------------------------------------------------------------------------
/cl/AUTHORS:
--------------------------------------------------------------------------------
1 | The following individuals have participated in the development of go-opencl
2 |
3 | Utkan Güngördü
4 | Paul Sbarra
5 | Michael Leimon
--------------------------------------------------------------------------------
/cl/CL/cl_d3d10.h:
--------------------------------------------------------------------------------
1 | /**********************************************************************************
2 | * Copyright (c) 2008-2010 The Khronos Group Inc.
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a
5 | * copy of this software and/or associated documentation files (the
6 | * "Materials"), to deal in the Materials without restriction, including
7 | * without limitation the rights to use, copy, modify, merge, publish,
8 | * distribute, sublicense, and/or sell copies of the Materials, and to
9 | * permit persons to whom the Materials are furnished to do so, subject to
10 | * the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included
13 | * in all copies or substantial portions of the Materials.
14 | *
15 | * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 | * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
22 | **********************************************************************************/
23 |
24 | /* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */
25 |
26 | #ifndef __OPENCL_CL_D3D10_H
27 | #define __OPENCL_CL_D3D10_H
28 |
29 | #include
30 | #include
31 | #include
32 |
33 | #ifdef __cplusplus
34 | extern "C" {
35 | #endif
36 |
37 | /******************************************************************************
38 | * cl_khr_d3d10_sharing */
39 | #define cl_khr_d3d10_sharing 1
40 |
41 | typedef cl_uint cl_d3d10_device_source_khr;
42 | typedef cl_uint cl_d3d10_device_set_khr;
43 |
44 | /******************************************************************************/
45 |
46 | // Error Codes
47 | #define CL_INVALID_D3D10_DEVICE_KHR -1002
48 | #define CL_INVALID_D3D10_RESOURCE_KHR -1003
49 | #define CL_D3D10_RESOURCE_ALREADY_ACQUIRED_KHR -1004
50 | #define CL_D3D10_RESOURCE_NOT_ACQUIRED_KHR -1005
51 |
52 | // cl_d3d10_device_source_nv
53 | #define CL_D3D10_DEVICE_KHR 0x4010
54 | #define CL_D3D10_DXGI_ADAPTER_KHR 0x4011
55 |
56 | // cl_d3d10_device_set_nv
57 | #define CL_PREFERRED_DEVICES_FOR_D3D10_KHR 0x4012
58 | #define CL_ALL_DEVICES_FOR_D3D10_KHR 0x4013
59 |
60 | // cl_context_info
61 | #define CL_CONTEXT_D3D10_DEVICE_KHR 0x4014
62 | #define CL_CONTEXT_D3D10_PREFER_SHARED_RESOURCES_KHR 0x402C
63 |
64 | // cl_mem_info
65 | #define CL_MEM_D3D10_RESOURCE_KHR 0x4015
66 |
67 | // cl_image_info
68 | #define CL_IMAGE_D3D10_SUBRESOURCE_KHR 0x4016
69 |
70 | // cl_command_type
71 | #define CL_COMMAND_ACQUIRE_D3D10_OBJECTS_KHR 0x4017
72 | #define CL_COMMAND_RELEASE_D3D10_OBJECTS_KHR 0x4018
73 |
74 | /******************************************************************************/
75 |
76 | typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetDeviceIDsFromD3D10KHR_fn)(
77 | cl_platform_id platform,
78 | cl_d3d10_device_source_khr d3d_device_source,
79 | void * d3d_object,
80 | cl_d3d10_device_set_khr d3d_device_set,
81 | cl_uint num_entries,
82 | cl_device_id * devices,
83 | cl_uint * num_devices) CL_API_SUFFIX__VERSION_1_0;
84 |
85 | typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10BufferKHR_fn)(
86 | cl_context context,
87 | cl_mem_flags flags,
88 | ID3D10Buffer * resource,
89 | cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
90 |
91 | typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10Texture2DKHR_fn)(
92 | cl_context context,
93 | cl_mem_flags flags,
94 | ID3D10Texture2D * resource,
95 | UINT subresource,
96 | cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
97 |
98 | typedef CL_API_ENTRY cl_mem (CL_API_CALL *clCreateFromD3D10Texture3DKHR_fn)(
99 | cl_context context,
100 | cl_mem_flags flags,
101 | ID3D10Texture3D * resource,
102 | UINT subresource,
103 | cl_int * errcode_ret) CL_API_SUFFIX__VERSION_1_0;
104 |
105 | typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueAcquireD3D10ObjectsKHR_fn)(
106 | cl_command_queue command_queue,
107 | cl_uint num_objects,
108 | const cl_mem * mem_objects,
109 | cl_uint num_events_in_wait_list,
110 | const cl_event * event_wait_list,
111 | cl_event * event) CL_API_SUFFIX__VERSION_1_0;
112 |
113 | typedef CL_API_ENTRY cl_int (CL_API_CALL *clEnqueueReleaseD3D10ObjectsKHR_fn)(
114 | cl_command_queue command_queue,
115 | cl_uint num_objects,
116 | cl_mem * mem_objects,
117 | cl_uint num_events_in_wait_list,
118 | const cl_event * event_wait_list,
119 | cl_event * event) CL_API_SUFFIX__VERSION_1_0;
120 |
121 | #ifdef __cplusplus
122 | }
123 | #endif
124 |
125 | #endif // __OPENCL_CL_D3D10_H
126 |
127 |
--------------------------------------------------------------------------------
/cl/CL/cl_ext.h:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright (c) 2008-2010 The Khronos Group Inc.
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a
5 | * copy of this software and/or associated documentation files (the
6 | * "Materials"), to deal in the Materials without restriction, including
7 | * without limitation the rights to use, copy, modify, merge, publish,
8 | * distribute, sublicense, and/or sell copies of the Materials, and to
9 | * permit persons to whom the Materials are furnished to do so, subject to
10 | * the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included
13 | * in all copies or substantial portions of the Materials.
14 | *
15 | * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 | * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
22 | ******************************************************************************/
23 |
24 | /* $Revision: 11928 $ on $Date: 2010-07-13 09:04:56 -0700 (Tue, 13 Jul 2010) $ */
25 |
26 | /* cl_ext.h contains OpenCL extensions which don't have external */
27 | /* (OpenGL, D3D) dependencies. */
28 |
29 | #ifndef __CL_EXT_H
30 | #define __CL_EXT_H
31 |
32 | #ifdef __cplusplus
33 | extern "C" {
34 | #endif
35 |
36 | #ifdef __APPLE__
37 | #include
38 | #include
39 | #else
40 | #include
41 | #endif
42 |
43 | /* cl_khr_fp64 extension - no extension #define since it has no functions */
44 | #define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032
45 |
46 | /* cl_khr_fp16 extension - no extension #define since it has no functions */
47 | #define CL_DEVICE_HALF_FP_CONFIG 0x1033
48 |
49 | /* Memory object destruction
50 | *
51 | * Apple extension for use to manage externally allocated buffers used with cl_mem objects with CL_MEM_USE_HOST_PTR
52 | *
53 | * Registers a user callback function that will be called when the memory object is deleted and its resources
54 | * freed. Each call to clSetMemObjectCallbackFn registers the specified user callback function on a callback
55 | * stack associated with memobj. The registered user callback functions are called in the reverse order in
56 | * which they were registered. The user callback functions are called and then the memory object is deleted
57 | * and its resources freed. This provides a mechanism for the application (and libraries) using memobj to be
58 | * notified when the memory referenced by host_ptr, specified when the memory object is created and used as
59 | * the storage bits for the memory object, can be reused or freed.
60 | *
61 | * The application may not call CL api's with the cl_mem object passed to the pfn_notify.
62 | *
63 | * Please check for the "cl_APPLE_SetMemObjectDestructor" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS)
64 | * before using.
65 | */
66 | #define cl_APPLE_SetMemObjectDestructor 1
67 | cl_int CL_API_ENTRY clSetMemObjectDestructorAPPLE( cl_mem /* memobj */,
68 | void (* /*pfn_notify*/)( cl_mem /* memobj */, void* /*user_data*/),
69 | void * /*user_data */ ) CL_EXT_SUFFIX__VERSION_1_0;
70 |
71 |
72 | /* Context Logging Functions
73 | *
74 | * The next three convenience functions are intended to be used as the pfn_notify parameter to clCreateContext().
75 | * Please check for the "cl_APPLE_ContextLoggingFunctions" extension using clGetDeviceInfo(CL_DEVICE_EXTENSIONS)
76 | * before using.
77 | *
78 | * clLogMessagesToSystemLog fowards on all log messages to the Apple System Logger
79 | */
80 | #define cl_APPLE_ContextLoggingFunctions 1
81 | extern void CL_API_ENTRY clLogMessagesToSystemLogAPPLE( const char * /* errstr */,
82 | const void * /* private_info */,
83 | size_t /* cb */,
84 | void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0;
85 |
86 | /* clLogMessagesToStdout sends all log messages to the file descriptor stdout */
87 | extern void CL_API_ENTRY clLogMessagesToStdoutAPPLE( const char * /* errstr */,
88 | const void * /* private_info */,
89 | size_t /* cb */,
90 | void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0;
91 |
92 | /* clLogMessagesToStderr sends all log messages to the file descriptor stderr */
93 | extern void CL_API_ENTRY clLogMessagesToStderrAPPLE( const char * /* errstr */,
94 | const void * /* private_info */,
95 | size_t /* cb */,
96 | void * /* user_data */ ) CL_EXT_SUFFIX__VERSION_1_0;
97 |
98 |
99 | /************************
100 | * cl_khr_icd extension *
101 | ************************/
102 | #define cl_khr_icd 1
103 |
104 | /* cl_platform_info */
105 | #define CL_PLATFORM_ICD_SUFFIX_KHR 0x0920
106 |
107 | /* Additional Error Codes */
108 | #define CL_PLATFORM_NOT_FOUND_KHR -1001
109 |
110 | extern CL_API_ENTRY cl_int CL_API_CALL
111 | clIcdGetPlatformIDsKHR(cl_uint /* num_entries */,
112 | cl_platform_id * /* platforms */,
113 | cl_uint * /* num_platforms */);
114 |
115 | typedef CL_API_ENTRY cl_int (CL_API_CALL *clIcdGetPlatformIDsKHR_fn)(
116 | cl_uint /* num_entries */,
117 | cl_platform_id * /* platforms */,
118 | cl_uint * /* num_platforms */);
119 |
120 |
121 | /******************************************
122 | * cl_nv_device_attribute_query extension *
123 | ******************************************/
124 | /* cl_nv_device_attribute_query extension - no extension #define since it has no functions */
125 | #define CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV 0x4000
126 | #define CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV 0x4001
127 | #define CL_DEVICE_REGISTERS_PER_BLOCK_NV 0x4002
128 | #define CL_DEVICE_WARP_SIZE_NV 0x4003
129 | #define CL_DEVICE_GPU_OVERLAP_NV 0x4004
130 | #define CL_DEVICE_KERNEL_EXEC_TIMEOUT_NV 0x4005
131 | #define CL_DEVICE_INTEGRATED_MEMORY_NV 0x4006
132 |
133 |
134 | /*********************************
135 | * cl_amd_device_attribute_query *
136 | *********************************/
137 | #define CL_DEVICE_PROFILING_TIMER_OFFSET_AMD 0x4036
138 |
139 |
140 | #ifdef CL_VERSION_1_1
141 | /***********************************
142 | * cl_ext_device_fission extension *
143 | ***********************************/
144 | #define cl_ext_device_fission 1
145 |
146 | extern CL_API_ENTRY cl_int CL_API_CALL
147 | clReleaseDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1;
148 |
149 | typedef CL_API_ENTRY cl_int
150 | (CL_API_CALL *clReleaseDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1;
151 |
152 | extern CL_API_ENTRY cl_int CL_API_CALL
153 | clRetainDeviceEXT( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1;
154 |
155 | typedef CL_API_ENTRY cl_int
156 | (CL_API_CALL *clRetainDeviceEXT_fn)( cl_device_id /*device*/ ) CL_EXT_SUFFIX__VERSION_1_1;
157 |
158 | typedef cl_ulong cl_device_partition_property_ext;
159 | extern CL_API_ENTRY cl_int CL_API_CALL
160 | clCreateSubDevicesEXT( cl_device_id /*in_device*/,
161 | const cl_device_partition_property_ext * /* properties */,
162 | cl_uint /*num_entries*/,
163 | cl_device_id * /*out_devices*/,
164 | cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1;
165 |
166 | typedef CL_API_ENTRY cl_int
167 | ( CL_API_CALL * clCreateSubDevicesEXT_fn)( cl_device_id /*in_device*/,
168 | const cl_device_partition_property_ext * /* properties */,
169 | cl_uint /*num_entries*/,
170 | cl_device_id * /*out_devices*/,
171 | cl_uint * /*num_devices*/ ) CL_EXT_SUFFIX__VERSION_1_1;
172 |
173 | /* cl_device_partition_property_ext */
174 | #define CL_DEVICE_PARTITION_EQUALLY_EXT 0x4050
175 | #define CL_DEVICE_PARTITION_BY_COUNTS_EXT 0x4051
176 | #define CL_DEVICE_PARTITION_BY_NAMES_EXT 0x4052
177 | #define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN_EXT 0x4053
178 |
179 | /* clDeviceGetInfo selectors */
180 | #define CL_DEVICE_PARENT_DEVICE_EXT 0x4054
181 | #define CL_DEVICE_PARTITION_TYPES_EXT 0x4055
182 | #define CL_DEVICE_AFFINITY_DOMAINS_EXT 0x4056
183 | #define CL_DEVICE_REFERENCE_COUNT_EXT 0x4057
184 | #define CL_DEVICE_PARTITION_STYLE_EXT 0x4058
185 |
186 | /* error codes */
187 | #define CL_DEVICE_PARTITION_FAILED_EXT -1057
188 | #define CL_INVALID_PARTITION_COUNT_EXT -1058
189 | #define CL_INVALID_PARTITION_NAME_EXT -1059
190 |
191 | /* CL_AFFINITY_DOMAINs */
192 | #define CL_AFFINITY_DOMAIN_L1_CACHE_EXT 0x1
193 | #define CL_AFFINITY_DOMAIN_L2_CACHE_EXT 0x2
194 | #define CL_AFFINITY_DOMAIN_L3_CACHE_EXT 0x3
195 | #define CL_AFFINITY_DOMAIN_L4_CACHE_EXT 0x4
196 | #define CL_AFFINITY_DOMAIN_NUMA_EXT 0x10
197 | #define CL_AFFINITY_DOMAIN_NEXT_FISSIONABLE_EXT 0x100
198 |
199 | /* cl_device_partition_property_ext list terminators */
200 | #define CL_PROPERTIES_LIST_END_EXT ((cl_device_partition_property_ext) 0)
201 | #define CL_PARTITION_BY_COUNTS_LIST_END_EXT ((cl_device_partition_property_ext) 0)
202 | #define CL_PARTITION_BY_NAMES_LIST_END_EXT ((cl_device_partition_property_ext) 0 - 1)
203 |
204 |
205 |
206 | #endif /* CL_VERSION_1_1 */
207 |
208 | #ifdef __cplusplus
209 | }
210 | #endif
211 |
212 |
213 | #endif /* __CL_EXT_H */
214 |
--------------------------------------------------------------------------------
/cl/CL/cl_gl.h:
--------------------------------------------------------------------------------
1 | /**********************************************************************************
2 | * Copyright (c) 2008-2010 The Khronos Group Inc.
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a
5 | * copy of this software and/or associated documentation files (the
6 | * "Materials"), to deal in the Materials without restriction, including
7 | * without limitation the rights to use, copy, modify, merge, publish,
8 | * distribute, sublicense, and/or sell copies of the Materials, and to
9 | * permit persons to whom the Materials are furnished to do so, subject to
10 | * the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included
13 | * in all copies or substantial portions of the Materials.
14 | *
15 | * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 | * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
22 | **********************************************************************************/
23 |
24 | /* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */
25 |
26 | /*
27 | * cl_gl.h contains Khronos-approved (KHR) OpenCL extensions which have
28 | * OpenGL dependencies. The application is responsible for #including
29 | * OpenGL or OpenGL ES headers before #including cl_gl.h.
30 | */
31 |
32 | #ifndef __OPENCL_CL_GL_H
33 | #define __OPENCL_CL_GL_H
34 |
35 | #ifdef __APPLE__
36 | #include
37 | #include
38 | #else
39 | #include
40 | #endif
41 |
42 | #ifdef __cplusplus
43 | extern "C" {
44 | #endif
45 |
46 | typedef cl_uint cl_gl_object_type;
47 | typedef cl_uint cl_gl_texture_info;
48 | typedef cl_uint cl_gl_platform_info;
49 | typedef struct __GLsync *cl_GLsync;
50 |
51 | /* cl_gl_object_type */
52 | #define CL_GL_OBJECT_BUFFER 0x2000
53 | #define CL_GL_OBJECT_TEXTURE2D 0x2001
54 | #define CL_GL_OBJECT_TEXTURE3D 0x2002
55 | #define CL_GL_OBJECT_RENDERBUFFER 0x2003
56 |
57 | /* cl_gl_texture_info */
58 | #define CL_GL_TEXTURE_TARGET 0x2004
59 | #define CL_GL_MIPMAP_LEVEL 0x2005
60 |
61 | extern CL_API_ENTRY cl_mem CL_API_CALL
62 | clCreateFromGLBuffer(cl_context /* context */,
63 | cl_mem_flags /* flags */,
64 | cl_GLuint /* bufobj */,
65 | int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
66 |
67 | extern CL_API_ENTRY cl_mem CL_API_CALL
68 | clCreateFromGLTexture2D(cl_context /* context */,
69 | cl_mem_flags /* flags */,
70 | cl_GLenum /* target */,
71 | cl_GLint /* miplevel */,
72 | cl_GLuint /* texture */,
73 | cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
74 |
75 | extern CL_API_ENTRY cl_mem CL_API_CALL
76 | clCreateFromGLTexture3D(cl_context /* context */,
77 | cl_mem_flags /* flags */,
78 | cl_GLenum /* target */,
79 | cl_GLint /* miplevel */,
80 | cl_GLuint /* texture */,
81 | cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
82 |
83 | extern CL_API_ENTRY cl_mem CL_API_CALL
84 | clCreateFromGLRenderbuffer(cl_context /* context */,
85 | cl_mem_flags /* flags */,
86 | cl_GLuint /* renderbuffer */,
87 | cl_int * /* errcode_ret */) CL_API_SUFFIX__VERSION_1_0;
88 |
89 | extern CL_API_ENTRY cl_int CL_API_CALL
90 | clGetGLObjectInfo(cl_mem /* memobj */,
91 | cl_gl_object_type * /* gl_object_type */,
92 | cl_GLuint * /* gl_object_name */) CL_API_SUFFIX__VERSION_1_0;
93 |
94 | extern CL_API_ENTRY cl_int CL_API_CALL
95 | clGetGLTextureInfo(cl_mem /* memobj */,
96 | cl_gl_texture_info /* param_name */,
97 | size_t /* param_value_size */,
98 | void * /* param_value */,
99 | size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
100 |
101 | extern CL_API_ENTRY cl_int CL_API_CALL
102 | clEnqueueAcquireGLObjects(cl_command_queue /* command_queue */,
103 | cl_uint /* num_objects */,
104 | const cl_mem * /* mem_objects */,
105 | cl_uint /* num_events_in_wait_list */,
106 | const cl_event * /* event_wait_list */,
107 | cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0;
108 |
109 | extern CL_API_ENTRY cl_int CL_API_CALL
110 | clEnqueueReleaseGLObjects(cl_command_queue /* command_queue */,
111 | cl_uint /* num_objects */,
112 | const cl_mem * /* mem_objects */,
113 | cl_uint /* num_events_in_wait_list */,
114 | const cl_event * /* event_wait_list */,
115 | cl_event * /* event */) CL_API_SUFFIX__VERSION_1_0;
116 |
117 | /* cl_khr_gl_sharing extension */
118 |
119 | #define cl_khr_gl_sharing 1
120 |
121 | typedef cl_uint cl_gl_context_info;
122 |
123 | /* Additional Error Codes */
124 | #define CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR -1000
125 |
126 | /* cl_gl_context_info */
127 | #define CL_CURRENT_DEVICE_FOR_GL_CONTEXT_KHR 0x2006
128 | #define CL_DEVICES_FOR_GL_CONTEXT_KHR 0x2007
129 |
130 | /* Additional cl_context_properties */
131 | #define CL_GL_CONTEXT_KHR 0x2008
132 | #define CL_EGL_DISPLAY_KHR 0x2009
133 | #define CL_GLX_DISPLAY_KHR 0x200A
134 | #define CL_WGL_HDC_KHR 0x200B
135 | #define CL_CGL_SHAREGROUP_KHR 0x200C
136 |
137 | extern CL_API_ENTRY cl_int CL_API_CALL
138 | clGetGLContextInfoKHR(const cl_context_properties * /* properties */,
139 | cl_gl_context_info /* param_name */,
140 | size_t /* param_value_size */,
141 | void * /* param_value */,
142 | size_t * /* param_value_size_ret */) CL_API_SUFFIX__VERSION_1_0;
143 |
144 | typedef CL_API_ENTRY cl_int (CL_API_CALL *clGetGLContextInfoKHR_fn)(
145 | const cl_context_properties * properties,
146 | cl_gl_context_info param_name,
147 | size_t param_value_size,
148 | void * param_value,
149 | size_t * param_value_size_ret);
150 |
151 | #ifdef __cplusplus
152 | }
153 | #endif
154 |
155 | #endif /* __OPENCL_CL_GL_H */
156 |
--------------------------------------------------------------------------------
/cl/CL/cl_gl_ext.h:
--------------------------------------------------------------------------------
1 | /**********************************************************************************
2 | * Copyright (c) 2008-2010 The Khronos Group Inc.
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a
5 | * copy of this software and/or associated documentation files (the
6 | * "Materials"), to deal in the Materials without restriction, including
7 | * without limitation the rights to use, copy, modify, merge, publish,
8 | * distribute, sublicense, and/or sell copies of the Materials, and to
9 | * permit persons to whom the Materials are furnished to do so, subject to
10 | * the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included
13 | * in all copies or substantial portions of the Materials.
14 | *
15 | * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 | * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
22 | **********************************************************************************/
23 |
24 | /* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */
25 |
26 | /* cl_gl_ext.h contains vendor (non-KHR) OpenCL extensions which have */
27 | /* OpenGL dependencies. */
28 |
29 | #ifndef __OPENCL_CL_GL_EXT_H
30 | #define __OPENCL_CL_GL_EXT_H
31 |
32 | #ifdef __cplusplus
33 | extern "C" {
34 | #endif
35 |
36 | #ifdef __APPLE__
37 | #include
38 | #else
39 | #include
40 | #endif
41 |
42 | /*
43 | * For each extension, follow this template
44 | * * cl_VEN_extname extension */
45 | /* #define cl_VEN_extname 1
46 | * ... define new types, if any
47 | * ... define new tokens, if any
48 | * ... define new APIs, if any
49 | *
50 | * If you need GLtypes here, mirror them with a cl_GLtype, rather than including a GL header
51 | * This allows us to avoid having to decide whether to include GL headers or GLES here.
52 | */
53 |
54 | /*
55 | * cl_khr_gl_event extension
56 | * See section 9.9 in the OpenCL 1.1 spec for more information
57 | */
58 | #define CL_COMMAND_GL_FENCE_SYNC_OBJECT_KHR 0x200D
59 |
60 | extern CL_API_ENTRY cl_event CL_API_CALL
61 | clCreateEventFromGLsyncKHR(cl_context /* context */,
62 | cl_GLsync /* cl_GLsync */,
63 | cl_int * /* errcode_ret */) CL_EXT_SUFFIX__VERSION_1_1;
64 |
65 | #ifdef __cplusplus
66 | }
67 | #endif
68 |
69 | #endif /* __OPENCL_CL_GL_EXT_H */
70 |
--------------------------------------------------------------------------------
/cl/CL/opencl.h:
--------------------------------------------------------------------------------
1 | /*******************************************************************************
2 | * Copyright (c) 2008-2010 The Khronos Group Inc.
3 | *
4 | * Permission is hereby granted, free of charge, to any person obtaining a
5 | * copy of this software and/or associated documentation files (the
6 | * "Materials"), to deal in the Materials without restriction, including
7 | * without limitation the rights to use, copy, modify, merge, publish,
8 | * distribute, sublicense, and/or sell copies of the Materials, and to
9 | * permit persons to whom the Materials are furnished to do so, subject to
10 | * the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included
13 | * in all copies or substantial portions of the Materials.
14 | *
15 | * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
16 | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17 | * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
18 | * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
19 | * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
20 | * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
21 | * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
22 | ******************************************************************************/
23 |
24 | /* $Revision: 11708 $ on $Date: 2010-06-13 23:36:24 -0700 (Sun, 13 Jun 2010) $ */
25 |
26 | #ifndef __OPENCL_H
27 | #define __OPENCL_H
28 |
29 | #ifdef __cplusplus
30 | extern "C" {
31 | #endif
32 |
33 | #ifdef __APPLE__
34 |
35 | #include
36 | #include
37 | #include
38 | #include
39 |
40 | #else
41 |
42 | #include
43 | #include
44 | #include
45 | #include
46 |
47 | #endif
48 |
49 | #ifdef __cplusplus
50 | }
51 | #endif
52 |
53 | #endif /* __OPENCL_H */
54 |
55 |
--------------------------------------------------------------------------------
/cl/buffer.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I . -Wno-error=deprecated-declarations
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 |
34 | */
35 | import "C"
36 |
37 | type Buffer struct {
38 | id C.cl_mem
39 | }
40 |
41 | func (b *Buffer) release() error {
42 | err := releaseMemObject(b.id)
43 | b.id = nil
44 | return err
45 | }
46 |
--------------------------------------------------------------------------------
/cl/commandQueue.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I CL -Wno-error=deprecated-declarations
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 |
34 |
35 | */
36 | import "C"
37 |
38 | import (
39 | "unsafe"
40 | )
41 |
42 | type CommandQueueParameter C.cl_command_queue_properties
43 |
44 | const (
45 | QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE CommandQueueParameter = C.CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE
46 | QUEUE_PROFILING_ENABLE CommandQueueParameter = C.CL_QUEUE_PROFILING_ENABLE
47 | QUEUE_NIL CommandQueueParameter = 0
48 | )
49 |
50 | type CommandQueue struct {
51 | id C.cl_command_queue
52 | }
53 |
54 | func (cq *CommandQueue) EnqueueKernel(k *Kernel, offset, gsize, lsize []Size) error {
55 |
56 | cptr := func(w []Size) *C.size_t {
57 | if len(w) == 0 {
58 | return nil
59 | }
60 | return (*C.size_t)(unsafe.Pointer(&w[0]))
61 | }
62 |
63 | c_offset := cptr(offset)
64 | c_gsize := cptr(gsize)
65 | c_lsize := cptr(lsize)
66 |
67 | if ret := C.clEnqueueNDRangeKernel(cq.id, k.id, C.cl_uint(len(gsize)), c_offset, c_gsize, c_lsize, 0, nil, nil); ret != C.CL_SUCCESS {
68 | return Cl_error(ret)
69 | }
70 | return nil
71 | }
72 |
73 | func (cq *CommandQueue) EnqueueReadBuffer(buf *Buffer, offset uint32, size uint32) ([]byte, error) {
74 | bytes := make([]byte, size)
75 | if ret := C.clEnqueueReadBuffer(cq.id, buf.id, C.CL_TRUE, C.size_t(offset), C.size_t(size), unsafe.Pointer(&bytes[0]), 0, nil, nil); ret != C.CL_SUCCESS {
76 | return nil, Cl_error(ret)
77 | }
78 | return bytes, nil
79 | }
80 |
81 | func (cq *CommandQueue) EnqueueWriteBuffer(buf *Buffer, data []byte, offset uint32) error {
82 |
83 | if ret := C.clEnqueueWriteBuffer(cq.id, buf.id, C.CL_TRUE, C.size_t(offset), C.size_t(len(data)), unsafe.Pointer(&data[0]), 0, nil, nil); ret != C.CL_SUCCESS {
84 | return Cl_error(ret)
85 | }
86 | return nil
87 | }
88 |
89 | func (cq *CommandQueue) EnqueueReadImage(i *Image, blocking bool, origin, region [3]Size, rowPitch, slicePitch Size) ([]byte, error) {
90 | c_blocking := C.cl_bool(C.CL_FALSE)
91 | if blocking {
92 | c_blocking = C.CL_TRUE
93 | }
94 |
95 | size := Size(0)
96 | if i.Property(IMAGE_DEPTH) == 0 || i.Property(IMAGE_DEPTH) == 1 { // 2D image
97 | if rowPitch == 0 {
98 | rowPitch = i.Property(IMAGE_WIDTH) * i.Property(IMAGE_ELEMENT_SIZE)
99 | }
100 | size = rowPitch * i.Property(IMAGE_HEIGHT)
101 | } else {
102 | if slicePitch == 0 {
103 | if rowPitch == 0 {
104 | rowPitch = i.Property(IMAGE_WIDTH) * i.Property(IMAGE_ELEMENT_SIZE)
105 | }
106 | slicePitch = rowPitch * i.Property(IMAGE_DEPTH)
107 | }
108 | size = slicePitch * i.Property(IMAGE_DEPTH)
109 | }
110 | bytes := make([]byte, size)
111 |
112 | if ret := C.clEnqueueReadImage(
113 | cq.id, i.id, c_blocking,
114 | (*C.size_t)(unsafe.Pointer(&origin[0])), (*C.size_t)(unsafe.Pointer(®ion[0])),
115 | C.size_t(rowPitch), C.size_t(slicePitch), unsafe.Pointer(&bytes[0]),
116 | 0, nil, nil); ret != C.CL_SUCCESS {
117 | return nil, Cl_error(ret)
118 | }
119 | return bytes, nil
120 | }
121 |
122 | func (cq *CommandQueue) EnqueueWriteImage(img *Image, blocking bool, origin, region [3]Size, rowPitch, slicePitch Size, data []byte) error {
123 | c_blocking := C.cl_bool(C.CL_FALSE)
124 | if blocking {
125 | c_blocking = C.CL_TRUE
126 | }
127 |
128 | if ret := C.clEnqueueWriteImage(
129 | cq.id, img.id, c_blocking,
130 | (*C.size_t)(unsafe.Pointer(&origin[0])), (*C.size_t)(unsafe.Pointer(®ion[0])),
131 | C.size_t(rowPitch), C.size_t(slicePitch),
132 | unsafe.Pointer(&data[0]),
133 | C.cl_uint(0), nil, nil); ret != C.CL_SUCCESS {
134 | return Cl_error(ret)
135 | }
136 | return nil
137 | }
138 |
139 | func (q *CommandQueue) release() error {
140 | if q.id != nil {
141 | if err := C.clReleaseCommandQueue(q.id); err != C.CL_SUCCESS {
142 | return Cl_error(err)
143 | }
144 | q.id = nil
145 | }
146 | return nil
147 | }
148 |
--------------------------------------------------------------------------------
/cl/context.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I CL -Wno-error=deprecated-declarations
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 |
34 | cl_context_properties PlatformToContextParameter(cl_platform_id platform) { return (cl_context_properties)platform; }
35 |
36 | */
37 | import "C"
38 |
39 | import (
40 | "io/ioutil"
41 | "runtime"
42 | "unsafe"
43 | )
44 |
45 | type ContextParameter C.cl_context_properties
46 |
47 | const (
48 | CONTEXT_PLATFORM ContextParameter = C.CL_CONTEXT_PLATFORM
49 | )
50 |
51 | type ContextProperty C.cl_context_info
52 |
53 | const (
54 | CONTEXT_REFERENCE_COUNT ContextProperty = C.CL_CONTEXT_REFERENCE_COUNT
55 | CONTEXT_NUM_DEVICES ContextProperty = C.CL_CONTEXT_NUM_DEVICES
56 | CONTEXT_DEVICES ContextProperty = C.CL_CONTEXT_DEVICES
57 | CONTEXT_PROPERTIES ContextProperty = C.CL_CONTEXT_PROPERTIES
58 | )
59 |
60 | func ContextProperties() []ContextProperty {
61 | return []ContextProperty{
62 | CONTEXT_REFERENCE_COUNT,
63 | CONTEXT_NUM_DEVICES,
64 | CONTEXT_DEVICES,
65 | CONTEXT_PROPERTIES}
66 | }
67 |
68 | type Context struct {
69 | id C.cl_context
70 | properties map[ContextProperty]interface{}
71 | }
72 |
73 | func createParameters(params map[ContextParameter]interface{}) ([]C.cl_context_properties, error) {
74 | c_params := make([]C.cl_context_properties, (len(params)<<1)+1)
75 | i := 0
76 | for param, value := range params {
77 | c_params[i] = C.cl_context_properties(param)
78 |
79 | switch param {
80 | case CONTEXT_PLATFORM:
81 | if v, ok := value.(Platform); ok {
82 | c_params[i+1] = C.PlatformToContextParameter(v.id)
83 | } else {
84 | return nil, Cl_error(C.CL_INVALID_VALUE)
85 | }
86 |
87 | default:
88 | return nil, Cl_error(C.CL_INVALID_VALUE)
89 | }
90 | i += 2
91 | }
92 | c_params[i] = 0
93 |
94 | return c_params, nil
95 | }
96 |
97 | func NewContextOfType(params map[ContextParameter]interface{}, t DeviceType) (*Context, error) {
98 | var c_params []C.cl_context_properties
99 | var propErr error
100 | if c_params, propErr = createParameters(params); propErr != nil {
101 | return nil, propErr
102 | }
103 |
104 | var c_context C.cl_context
105 | var err C.cl_int
106 | if c_context = C.clCreateContextFromType(&c_params[0], C.cl_device_type(t), nil, nil, &err); err != C.CL_SUCCESS {
107 | return nil, Cl_error(err)
108 | }
109 | c := &Context{id: c_context, properties: make(map[ContextProperty]interface{})}
110 | runtime.SetFinalizer(c, (*Context).release)
111 |
112 | return c, nil
113 | }
114 |
115 | func NewContextOfDevices(params map[ContextParameter]interface{}, devices []Device) (*Context, error) {
116 | var c_params []C.cl_context_properties
117 | var propErr error
118 | if c_params, propErr = createParameters(params); propErr != nil {
119 | return nil, propErr
120 | }
121 |
122 | c_devices := make([]C.cl_device_id, len(devices))
123 | for i, device := range devices {
124 | c_devices[i] = device.id
125 | }
126 |
127 | var c_context C.cl_context
128 | var err C.cl_int
129 | if c_context = C.clCreateContext(&c_params[0], C.cl_uint(len(c_devices)), &c_devices[0], nil, nil, &err); err != C.CL_SUCCESS {
130 | return nil, Cl_error(err)
131 | }
132 | c := &Context{id: c_context, properties: make(map[ContextProperty]interface{})}
133 | runtime.SetFinalizer(c, (*Context).release)
134 |
135 | return c, nil
136 | }
137 |
138 | func (c *Context) Property(prop ContextProperty) interface{} {
139 | if value, ok := c.properties[prop]; ok {
140 | return value
141 | }
142 |
143 | var data interface{}
144 | var length C.size_t
145 | var ret C.cl_int
146 |
147 | switch prop {
148 | case CONTEXT_REFERENCE_COUNT,
149 | CONTEXT_NUM_DEVICES:
150 | var val C.cl_uint
151 | ret = C.clGetContextInfo(c.id, C.cl_context_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
152 | data = val
153 |
154 | case CONTEXT_DEVICES:
155 | if data := c.Property(CONTEXT_NUM_DEVICES); data == nil {
156 | return nil
157 | } else {
158 | num_devs := data.(C.cl_uint)
159 | c_devs := make([]C.cl_device_id, num_devs)
160 | if ret = C.clGetContextInfo(c.id, C.cl_context_info(prop), C.size_t(num_devs*C.cl_uint(unsafe.Sizeof(c_devs[0]))), unsafe.Pointer(&c_devs[0]), &length); ret != C.CL_SUCCESS {
161 | return nil
162 | }
163 | devs := make([]Device, length/C.size_t(unsafe.Sizeof(c_devs[0])))
164 | for i, val := range c_devs {
165 | devs[i].id = val
166 | }
167 | data = devs
168 | }
169 |
170 | default:
171 | return nil
172 | }
173 |
174 | if ret != C.CL_SUCCESS {
175 | return nil
176 | }
177 | c.properties[prop] = data
178 | return c.properties[prop]
179 | }
180 |
181 | func (c *Context) NewCommandQueue(device Device, param CommandQueueParameter) (*CommandQueue, error) {
182 | var c_queue C.cl_command_queue
183 | var err C.cl_int
184 | if c_queue = C.clCreateCommandQueue(c.id, device.id, C.cl_command_queue_properties(param), &err); err != C.CL_SUCCESS {
185 | return nil, Cl_error(err)
186 | }
187 | queue := &CommandQueue{id: c_queue}
188 | runtime.SetFinalizer(queue, (*CommandQueue).release)
189 |
190 | return queue, nil
191 | }
192 |
193 | func (c *Context) NewProgramFromSource(prog []byte) (*Program, error) {
194 | var c_program C.cl_program
195 | var err C.cl_int
196 |
197 | srcPtr := (*C.char)(unsafe.Pointer(&prog[0]))
198 | length := (C.size_t)(len(prog))
199 | if c_program = C.clCreateProgramWithSource(c.id, 1, &srcPtr, &length, &err); err != C.CL_SUCCESS {
200 | return nil, Cl_error(err)
201 | }
202 |
203 | program := &Program{id: c_program}
204 | runtime.SetFinalizer(program, (*Program).release)
205 |
206 | return program, nil
207 | }
208 |
209 | func (c *Context) NewProgramFromFile(filename string) (*Program, error) {
210 | content, err := ioutil.ReadFile(filename)
211 | if err != nil {
212 | return nil, err
213 | }
214 | return c.NewProgramFromSource(content)
215 | }
216 |
217 | func (c *Context) NewBuffer(flags MemoryFlags, size uint32) (*Buffer, error) {
218 | var c_buffer C.cl_mem
219 | var err C.cl_int
220 |
221 | if c_buffer = C.clCreateBuffer(c.id, C.cl_mem_flags(flags), C.size_t(size), nil, &err); err != C.CL_SUCCESS {
222 | return nil, Cl_error(err)
223 | }
224 |
225 | buffer := &Buffer{id: c_buffer}
226 | runtime.SetFinalizer(buffer, (*Buffer).release)
227 |
228 | return buffer, nil
229 | }
230 |
231 | func (c *Context) NewImage2D(flags MemoryFlags, format ImageFormat, width, height, rowPitch uint32, data *byte) (*Image, error) {
232 | var c_buffer C.cl_mem
233 | var err C.cl_int
234 |
235 | c_format := &C.cl_image_format{
236 | image_channel_order: C.cl_channel_order(format.ChannelOrder),
237 | image_channel_data_type: C.cl_channel_type(format.ChannelDataType)}
238 |
239 | if c_buffer = C.clCreateImage2D(c.id, C.cl_mem_flags(flags), c_format, C.size_t(width), C.size_t(height), C.size_t(rowPitch), unsafe.Pointer(data), &err); err != C.CL_SUCCESS {
240 | return nil, Cl_error(err)
241 | }
242 |
243 | image := &Image{id: c_buffer, format: format, properties: make(map[ImageProperty]Size)}
244 | runtime.SetFinalizer(image, (*Image).release)
245 |
246 | return image, nil
247 | }
248 |
249 | func (c *Context) NewImage3D(flags MemoryFlags, format ImageFormat, width, height, depth, rowPitch, slicePitch uint32, data *byte) (*Image, error) {
250 | var c_buffer C.cl_mem
251 | var err C.cl_int
252 |
253 | c_format := &C.cl_image_format{
254 | image_channel_order: C.cl_channel_order(format.ChannelOrder),
255 | image_channel_data_type: C.cl_channel_type(format.ChannelDataType)}
256 |
257 | if c_buffer = C.clCreateImage3D(c.id, C.cl_mem_flags(flags), c_format, C.size_t(width), C.size_t(height), C.size_t(depth), C.size_t(rowPitch), C.size_t(slicePitch), unsafe.Pointer(data), &err); err != C.CL_SUCCESS {
258 | return nil, Cl_error(err)
259 | }
260 |
261 | image := &Image{id: c_buffer, format: format, properties: make(map[ImageProperty]Size)}
262 | runtime.SetFinalizer(image, (*Image).release)
263 |
264 | return image, nil
265 | }
266 |
267 | func (c *Context) NewSampler(normalizedCoords bool, addressingMode AddressingMode, filterMode FilterMode) (*Sampler, error) {
268 | var c_sampler C.cl_sampler
269 | var err C.cl_int
270 |
271 | cNormalizedCoords := C.cl_bool(C.CL_FALSE)
272 | if normalizedCoords {
273 | cNormalizedCoords = C.CL_TRUE
274 | }
275 |
276 | if c_sampler = C.clCreateSampler(c.id, cNormalizedCoords, C.cl_addressing_mode(addressingMode), C.cl_filter_mode(filterMode), &err); err != C.CL_SUCCESS {
277 | return nil, Cl_error(err)
278 | }
279 |
280 | sampler := &Sampler{id: c_sampler, properties: make(map[SamplerProperty]interface{})}
281 | runtime.SetFinalizer(sampler, (*Sampler).release)
282 |
283 | return sampler, nil
284 | }
285 |
286 | func (c *Context) release() error {
287 | if c.id != nil {
288 | if err := C.clReleaseContext(c.id); err != C.CL_SUCCESS {
289 | return Cl_error(err)
290 | }
291 | c.id = nil
292 | }
293 | return nil
294 | }
295 |
--------------------------------------------------------------------------------
/cl/device.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I CL
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 |
34 | */
35 | import "C"
36 |
37 | import (
38 | "unsafe"
39 | )
40 |
41 | type DeviceType C.cl_device_type
42 |
43 | const (
44 | DEVICE_TYPE_DEFAULT DeviceType = C.CL_DEVICE_TYPE_DEFAULT
45 | DEVICE_TYPE_CPU DeviceType = C.CL_DEVICE_TYPE_CPU
46 | DEVICE_TYPE_GPU DeviceType = C.CL_DEVICE_TYPE_GPU
47 | DEVICE_TYPE_ACCELERATOR DeviceType = C.CL_DEVICE_TYPE_ACCELERATOR
48 | //DEVICE_TYPE_CUSTOM DeviceType = C.CL_DEVICE_TYPE_CUSTOM
49 | DEVICE_TYPE_ALL DeviceType = C.CL_DEVICE_TYPE_ALL
50 | )
51 |
52 | func (t DeviceType) String() string {
53 | mesg := deviceTypeMesg[t]
54 | if mesg == "" {
55 | return t.String()
56 | }
57 | return mesg
58 | }
59 |
60 | var deviceTypeMesg = map[DeviceType]string{
61 | DEVICE_TYPE_CPU: "CPU",
62 | DEVICE_TYPE_GPU: "GPU",
63 | DEVICE_TYPE_ACCELERATOR: "Accelerator",
64 | //DEVICE_TYPE_CUSTOM: "Custom",
65 | }
66 |
67 | type DeviceProperty C.cl_device_info
68 |
69 | const (
70 | DEVICE_ADDRESS_BITS DeviceProperty = C.CL_DEVICE_ADDRESS_BITS
71 | DEVICE_AVAILABLE DeviceProperty = C.CL_DEVICE_AVAILABLE
72 | //DEVICE_BUILT_IN_KERNELS DeviceProperty = C.CL_DEVICE_BUILT_IN_KERNELS
73 | DEVICE_COMPILER_AVAILABLE DeviceProperty = C.CL_DEVICE_COMPILER_AVAILABLE
74 | //DEVICE_DOUBLE_FP_CONFIG DeviceProperty = C.CL_DEVICE_DOUBLE_FP_CONFIG
75 | DEVICE_ENDIAN_LITTLE DeviceProperty = C.CL_DEVICE_ENDIAN_LITTLE
76 | DEVICE_ERROR_CORRECTION_SUPPORT DeviceProperty = C.CL_DEVICE_ERROR_CORRECTION_SUPPORT
77 | DEVICE_EXECUTION_CAPABILITIES DeviceProperty = C.CL_DEVICE_EXECUTION_CAPABILITIES
78 | DEVICE_EXTENSIONS DeviceProperty = C.CL_DEVICE_EXTENSIONS
79 | DEVICE_GLOBAL_MEM_CACHE_SIZE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_CACHE_SIZE
80 | DEVICE_GLOBAL_MEM_CACHE_TYPE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_CACHE_TYPE
81 | DEVICE_GLOBAL_MEM_CACHELINE_SIZE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE
82 | DEVICE_GLOBAL_MEM_SIZE DeviceProperty = C.CL_DEVICE_GLOBAL_MEM_SIZE
83 | //DEVICE_HALF_FP_CONFIG DeviceProperty = C.CL_DEVICE_HALF_FP_CONFIG
84 | DEVICE_HOST_UNIFIED_MEMORY DeviceProperty = C.CL_DEVICE_HOST_UNIFIED_MEMORY
85 | DEVICE_IMAGE_SUPPORT DeviceProperty = C.CL_DEVICE_IMAGE_SUPPORT
86 | DEVICE_IMAGE2D_MAX_HEIGHT DeviceProperty = C.CL_DEVICE_IMAGE2D_MAX_HEIGHT
87 | DEVICE_IMAGE2D_MAX_WIDTH DeviceProperty = C.CL_DEVICE_IMAGE2D_MAX_WIDTH
88 | DEVICE_IMAGE3D_MAX_DEPTH DeviceProperty = C.CL_DEVICE_IMAGE3D_MAX_DEPTH
89 | DEVICE_IMAGE3D_MAX_HEIGHT DeviceProperty = C.CL_DEVICE_IMAGE3D_MAX_HEIGHT
90 | DEVICE_IMAGE3D_MAX_WIDTH DeviceProperty = C.CL_DEVICE_IMAGE3D_MAX_WIDTH
91 | //DEVICE_IMAGE_MAX_BUFFER_SIZE DeviceProperty = C.CL_DEVICE_IMAGE_MAX_BUFFER_SIZE
92 | //DEVICE_IMAGE_MAX_ARRAY_SIZE DeviceProperty = C.CL_DEVICE_IMAGE_MAX_ARRAY_SIZE
93 | //DEVICE_LINKER_AVAILABLE DeviceProperty = C.CL_DEVICE_LINKER_AVAILABLE
94 | DEVICE_LOCAL_MEM_SIZE DeviceProperty = C.CL_DEVICE_LOCAL_MEM_SIZE
95 | DEVICE_LOCAL_MEM_TYPE DeviceProperty = C.CL_DEVICE_LOCAL_MEM_TYPE
96 | DEVICE_MAX_CLOCK_FREQUENCY DeviceProperty = C.CL_DEVICE_MAX_CLOCK_FREQUENCY
97 | DEVICE_MAX_COMPUTE_UNITS DeviceProperty = C.CL_DEVICE_MAX_COMPUTE_UNITS
98 | DEVICE_MAX_CONSTANT_ARGS DeviceProperty = C.CL_DEVICE_MAX_CONSTANT_ARGS
99 | DEVICE_MAX_CONSTANT_BUFFER_SIZE DeviceProperty = C.CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE
100 | DEVICE_MAX_MEM_ALLOC_SIZE DeviceProperty = C.CL_DEVICE_MAX_MEM_ALLOC_SIZE
101 | DEVICE_MAX_PARAMETER_SIZE DeviceProperty = C.CL_DEVICE_MAX_PARAMETER_SIZE
102 | DEVICE_MAX_READ_IMAGE_ARGS DeviceProperty = C.CL_DEVICE_MAX_READ_IMAGE_ARGS
103 | DEVICE_MAX_SAMPLERS DeviceProperty = C.CL_DEVICE_MAX_SAMPLERS
104 | DEVICE_MAX_WORK_GROUP_SIZE DeviceProperty = C.CL_DEVICE_MAX_WORK_GROUP_SIZE
105 | DEVICE_MAX_WORK_ITEM_DIMENSIONS DeviceProperty = C.CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS
106 | DEVICE_MAX_WORK_ITEM_SIZES DeviceProperty = C.CL_DEVICE_MAX_WORK_ITEM_SIZES
107 | DEVICE_MAX_WRITE_IMAGE_ARGS DeviceProperty = C.CL_DEVICE_MAX_WRITE_IMAGE_ARGS
108 | DEVICE_MEM_BASE_ADDR_ALIGN DeviceProperty = C.CL_DEVICE_MEM_BASE_ADDR_ALIGN
109 | DEVICE_MIN_DATA_TYPE_ALIGN_SIZE DeviceProperty = C.CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE
110 | DEVICE_NAME DeviceProperty = C.CL_DEVICE_NAME
111 | DEVICE_NATIVE_VECTOR_WIDTH_CHAR DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR
112 | DEVICE_NATIVE_VECTOR_WIDTH_SHORT DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT
113 | DEVICE_NATIVE_VECTOR_WIDTH_INT DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_INT
114 | DEVICE_NATIVE_VECTOR_WIDTH_LONG DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG
115 | DEVICE_NATIVE_VECTOR_WIDTH_FLOAT DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT
116 | DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE
117 | DEVICE_NATIVE_VECTOR_WIDTH_HALF DeviceProperty = C.CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF
118 | DEVICE_OPENCL_C_VERSION DeviceProperty = C.CL_DEVICE_OPENCL_C_VERSION
119 | //DEVICE_PARENT_DEVICE DeviceProperty = C.CL_DEVICE_PARENT_DEVICE
120 | //DEVICE_PARTITION_MAX_SUB_DEVICES DeviceProperty = C.CL_DEVICE_PARTITION_MAX_SUB_DEVICES
121 | //DEVICE_PARTITION_PROPERTIES DeviceProperty = C.CL_DEVICE_PARTITION_PROPERTIES
122 | //DEVICE_PARTITION_AFFINITY_DOMAIN DeviceProperty = C.CL_DEVICE_PARTITION_AFFINITY_DOMAIN
123 | //DEVICE_PARTITION_TYPE DeviceProperty = C.CL_DEVICE_PARTITION_TYPE
124 | DEVICE_PLATFORM DeviceProperty = C.CL_DEVICE_PLATFORM
125 | DEVICE_PREFERRED_VECTOR_WIDTH_CHAR DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR
126 | DEVICE_PREFERRED_VECTOR_WIDTH_SHORT DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT
127 | DEVICE_PREFERRED_VECTOR_WIDTH_INT DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT
128 | DEVICE_PREFERRED_VECTOR_WIDTH_LONG DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG
129 | DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT
130 | DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE
131 | DEVICE_PREFERRED_VECTOR_WIDTH_HALF DeviceProperty = C.CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF
132 | //DEVICE_PRINTF_BUFFER_SIZE DeviceProperty = C.CL_DEVICE_PRINTF_BUFFER_SIZE
133 | //DEVICE_PREFERRED_INTEROP_USER_SYNC DeviceProperty = C.CL_DEVICE_PREFERRED_INTEROP_USER_SYNC
134 | DEVICE_PROFILE DeviceProperty = C.CL_DEVICE_PROFILE
135 | DEVICE_PROFILING_TIMER_RESOLUTION DeviceProperty = C.CL_DEVICE_PROFILING_TIMER_RESOLUTION
136 | DEVICE_QUEUE_PROPERTIES DeviceProperty = C.CL_DEVICE_QUEUE_PROPERTIES
137 | //DEVICE_REFERENCE_COUNT DeviceProperty = C.CL_DEVICE_REFERENCE_COUNT
138 | DEVICE_SINGLE_FP_CONFIG DeviceProperty = C.CL_DEVICE_SINGLE_FP_CONFIG
139 | DEVICE_TYPE DeviceProperty = C.CL_DEVICE_TYPE
140 | DEVICE_VENDOR DeviceProperty = C.CL_DEVICE_VENDOR
141 | DEVICE_VENDOR_ID DeviceProperty = C.CL_DEVICE_VENDOR_ID
142 | DEVICE_VERSION DeviceProperty = C.CL_DEVICE_VERSION
143 | DRIVER_VERSION DeviceProperty = C.CL_DRIVER_VERSION
144 | )
145 |
146 | type Device struct {
147 | id C.cl_device_id
148 | properties map[DeviceProperty]interface{}
149 | }
150 |
151 | func (d *Device) Property(prop DeviceProperty) interface{} {
152 | if value, ok := d.properties[prop]; ok {
153 | return value
154 | }
155 |
156 | var data interface{}
157 | var length C.size_t
158 | var ret C.cl_int
159 |
160 | switch prop {
161 | case DEVICE_AVAILABLE,
162 | DEVICE_COMPILER_AVAILABLE,
163 | DEVICE_ENDIAN_LITTLE,
164 | DEVICE_ERROR_CORRECTION_SUPPORT,
165 | DEVICE_HOST_UNIFIED_MEMORY,
166 | DEVICE_IMAGE_SUPPORT:
167 | //DEVICE_LINKER_AVAILABLE,
168 | //DEVICE_PREFERRED_INTEROP_USER_SYNC:
169 | var val C.cl_bool
170 | ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
171 | data = val == C.CL_TRUE
172 |
173 | case DEVICE_ADDRESS_BITS,
174 | DEVICE_MAX_CLOCK_FREQUENCY,
175 | DEVICE_MAX_COMPUTE_UNITS,
176 | DEVICE_MAX_CONSTANT_ARGS,
177 | DEVICE_MAX_READ_IMAGE_ARGS,
178 | DEVICE_MAX_SAMPLERS,
179 | DEVICE_MAX_WORK_ITEM_DIMENSIONS,
180 | DEVICE_MAX_WRITE_IMAGE_ARGS,
181 | DEVICE_MEM_BASE_ADDR_ALIGN,
182 | DEVICE_MIN_DATA_TYPE_ALIGN_SIZE,
183 | DEVICE_NATIVE_VECTOR_WIDTH_CHAR,
184 | DEVICE_NATIVE_VECTOR_WIDTH_SHORT,
185 | DEVICE_NATIVE_VECTOR_WIDTH_INT,
186 | DEVICE_NATIVE_VECTOR_WIDTH_LONG,
187 | DEVICE_NATIVE_VECTOR_WIDTH_FLOAT,
188 | DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE,
189 | DEVICE_NATIVE_VECTOR_WIDTH_HALF,
190 | //DEVICE_PARTITION_MAX_SUB_DEVICES,
191 | DEVICE_PREFERRED_VECTOR_WIDTH_CHAR,
192 | DEVICE_PREFERRED_VECTOR_WIDTH_SHORT,
193 | DEVICE_PREFERRED_VECTOR_WIDTH_INT,
194 | DEVICE_PREFERRED_VECTOR_WIDTH_LONG,
195 | DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT,
196 | DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE,
197 | DEVICE_PREFERRED_VECTOR_WIDTH_HALF,
198 | //DEVICE_REFERENCE_COUNT,
199 | DEVICE_VENDOR_ID:
200 | var val C.cl_uint
201 | ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
202 | data = val
203 |
204 | case DEVICE_IMAGE2D_MAX_HEIGHT,
205 | DEVICE_IMAGE2D_MAX_WIDTH,
206 | DEVICE_IMAGE3D_MAX_DEPTH,
207 | DEVICE_IMAGE3D_MAX_HEIGHT,
208 | DEVICE_IMAGE3D_MAX_WIDTH,
209 | //DEVICE_IMAGE_MAX_BUFFER_SIZE,
210 | //DEVICE_IMAGE_MAX_ARRAY_SIZE,
211 | DEVICE_MAX_PARAMETER_SIZE,
212 | DEVICE_MAX_WORK_GROUP_SIZE,
213 | //DEVICE_PRINTF_BUFFER_SIZE,
214 | DEVICE_PROFILING_TIMER_RESOLUTION:
215 | var val C.size_t
216 | ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
217 | data = val
218 |
219 | case DEVICE_GLOBAL_MEM_CACHE_SIZE,
220 | DEVICE_GLOBAL_MEM_SIZE,
221 | DEVICE_LOCAL_MEM_SIZE,
222 | DEVICE_MAX_CONSTANT_BUFFER_SIZE,
223 | DEVICE_MAX_MEM_ALLOC_SIZE:
224 | var val C.cl_ulong
225 | ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
226 | data = val
227 |
228 | /*case DEVICE_PLATFORM:
229 | var val C.cl_platform_id
230 | ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
231 | data = Platform{id: val}*/
232 |
233 | /*case DEVICE_PARENT_DEVICE:
234 | var val C.cl_device_id
235 | ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
236 | data = Device{id: val}*/
237 |
238 | case DEVICE_TYPE:
239 | var val C.cl_device_type
240 | ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
241 | data = DeviceType(val)
242 |
243 | case //DEVICE_BUILT_IN_KERNELS,
244 | DEVICE_EXTENSIONS,
245 | DEVICE_NAME,
246 | DEVICE_OPENCL_C_VERSION,
247 | DEVICE_PROFILE,
248 | DEVICE_VENDOR,
249 | DEVICE_VERSION,
250 | DRIVER_VERSION:
251 | if ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), 0, nil, &length); ret != C.CL_SUCCESS || length < 1 {
252 | data = ""
253 | break
254 | }
255 |
256 | buf := make([]C.char, length)
257 | if ret = C.clGetDeviceInfo(d.id, C.cl_device_info(prop), length, unsafe.Pointer(&buf[0]), &length); ret != C.CL_SUCCESS || length < 1 {
258 | data = ""
259 | break
260 | }
261 | data = C.GoStringN(&buf[0], C.int(length-1))
262 |
263 | default:
264 | return nil
265 | }
266 |
267 | if ret != C.CL_SUCCESS {
268 | return nil
269 | }
270 | d.properties[prop] = data
271 | return d.properties[prop]
272 | }
273 |
--------------------------------------------------------------------------------
/cl/image.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I CL
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 | */
34 | import "C"
35 |
36 | import (
37 | "unsafe"
38 | )
39 |
40 | type channelOrder C.cl_channel_order
41 |
42 | const (
43 | R channelOrder = C.CL_R
44 | A channelOrder = C.CL_A
45 | RG channelOrder = C.CL_RG
46 | RA channelOrder = C.CL_RA
47 | RGB channelOrder = C.CL_RGB
48 | RGBA channelOrder = C.CL_RGBA
49 | BGRA channelOrder = C.CL_BGRA
50 | ARGB channelOrder = C.CL_ARGB
51 | INTENSITY channelOrder = C.CL_INTENSITY
52 | LUMINANCE channelOrder = C.CL_LUMINANCE
53 | Rx channelOrder = C.CL_Rx
54 | RGx channelOrder = C.CL_RGx
55 | RGBx channelOrder = C.CL_RGBx
56 | )
57 |
58 | type channelType C.cl_channel_type
59 |
60 | const (
61 | FLOAT channelType = C.CL_FLOAT
62 | HALF_FLOAT channelType = C.CL_HALF_FLOAT
63 | SIGNED_INT8 channelType = C.CL_SIGNED_INT8
64 | SIGNED_INT16 channelType = C.CL_SIGNED_INT16
65 | SIGNED_INT32 channelType = C.CL_SIGNED_INT32
66 | SNORM_INT8 channelType = C.CL_SNORM_INT8
67 | SNORM_INT16 channelType = C.CL_SNORM_INT16
68 | UNORM_INT8 channelType = C.CL_UNORM_INT8
69 | UNORM_INT16 channelType = C.CL_UNORM_INT16
70 | UNORM_SHORT_565 channelType = C.CL_UNORM_SHORT_565
71 | UNORM_SHORT_555 channelType = C.CL_UNORM_SHORT_555
72 | UNORM_INT_101010 channelType = C.CL_UNORM_INT_101010
73 | UNSIGNED_INT8 channelType = C.CL_UNSIGNED_INT8
74 | UNSIGNED_INT16 channelType = C.CL_UNSIGNED_INT16
75 | UNSIGNED_INT32 channelType = C.CL_UNSIGNED_INT32
76 | )
77 |
78 | type ImageFormat struct {
79 | ChannelOrder channelOrder
80 | ChannelDataType channelType
81 | }
82 |
83 | type ImageProperty C.cl_image_info
84 |
85 | const (
86 | //IMAGE_FORMAT ImageProperty = C.CL_IMAGE_FORMAT
87 | IMAGE_ELEMENT_SIZE ImageProperty = C.CL_IMAGE_ELEMENT_SIZE
88 | IMAGE_ROW_PITCH ImageProperty = C.CL_IMAGE_ROW_PITCH
89 | IMAGE_SLICE_PITCH ImageProperty = C.CL_IMAGE_SLICE_PITCH
90 | IMAGE_WIDTH ImageProperty = C.CL_IMAGE_WIDTH
91 | IMAGE_HEIGHT ImageProperty = C.CL_IMAGE_HEIGHT
92 | IMAGE_DEPTH ImageProperty = C.CL_IMAGE_DEPTH
93 | )
94 |
95 | type Image struct {
96 | id C.cl_mem
97 | format ImageFormat
98 | properties map[ImageProperty]Size
99 | }
100 |
101 | func (i *Image) Format() ImageFormat {
102 | return i.format
103 | }
104 |
105 | func (i *Image) Property(prop ImageProperty) Size {
106 | if value, ok := i.properties[prop]; ok {
107 | return value
108 | }
109 |
110 | var data C.size_t
111 | var length C.size_t
112 |
113 | if ret := C.clGetImageInfo(i.id, C.cl_image_info(prop), C.size_t(unsafe.Sizeof(data)), unsafe.Pointer(&data), &length); ret != C.CL_SUCCESS {
114 | return 0
115 | }
116 |
117 | i.properties[prop] = Size(data)
118 | return i.properties[prop]
119 | }
120 |
121 | func (im *Image) release() error {
122 | err := releaseMemObject(im.id)
123 | im.id = nil
124 | return err
125 | }
126 |
--------------------------------------------------------------------------------
/cl/kernel.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I CL
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 |
34 | */
35 | import "C"
36 |
37 | import (
38 | "unsafe"
39 | )
40 |
41 | type Kernel struct {
42 | id C.cl_kernel
43 | }
44 |
45 | func (k *Kernel) SetArg(index uint, arg interface{}) error {
46 | var ret C.cl_int
47 |
48 | switch t := arg.(type) {
49 | case *Buffer:
50 | ret = C.clSetKernelArg(k.id, C.cl_uint(index), C.size_t(unsafe.Sizeof(t.id)), unsafe.Pointer(&t.id))
51 | case *Image:
52 | ret = C.clSetKernelArg(k.id, C.cl_uint(index), C.size_t(unsafe.Sizeof(t.id)), unsafe.Pointer(&t.id))
53 | case *Sampler:
54 | ret = C.clSetKernelArg(k.id, C.cl_uint(index), C.size_t(unsafe.Sizeof(t.id)), unsafe.Pointer(&t.id))
55 | case float32:
56 | f := C.float(t)
57 | ret = C.clSetKernelArg(k.id, C.cl_uint(index), C.size_t(unsafe.Sizeof(f)), unsafe.Pointer(&f))
58 |
59 | default:
60 | return Cl_error(C.CL_INVALID_VALUE)
61 | }
62 |
63 | if ret != C.CL_SUCCESS {
64 | return Cl_error(ret)
65 | }
66 | return nil
67 | }
68 |
69 | func (k *Kernel) SetArgs(offset uint, args []interface{}) error {
70 | for i, arg := range args {
71 | if err := k.SetArg(offset+uint(i), arg); err != nil {
72 | return err
73 | }
74 | }
75 | return nil
76 | }
77 |
78 | func (k *Kernel) release() error {
79 | if k.id != nil {
80 | if err := C.clReleaseKernel(k.id); err != C.CL_SUCCESS {
81 | return Cl_error(err)
82 | }
83 | k.id = nil
84 | }
85 | return nil
86 | }
87 |
--------------------------------------------------------------------------------
/cl/memory.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I CL
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 | */
34 | import "C"
35 |
36 | type MemoryType C.cl_mem_object_type
37 |
38 | const (
39 | MEM_OBJECT_BUFFER MemoryType = C.CL_MEM_OBJECT_BUFFER
40 | MEM_OBJECT_IMAGE2D MemoryType = C.CL_MEM_OBJECT_IMAGE2D
41 | MEM_OBJECT_IMAGE3D MemoryType = C.CL_MEM_OBJECT_IMAGE3D
42 | )
43 |
44 | type MemoryFlags C.cl_mem_flags
45 |
46 | const (
47 | MEM_READ_WRITE MemoryFlags = C.CL_MEM_READ_WRITE
48 | MEM_WRITE_ONLY MemoryFlags = C.CL_MEM_WRITE_ONLY
49 | MEM_READ_ONLY MemoryFlags = C.CL_MEM_READ_ONLY
50 | MEM_USE_HOST_PTR MemoryFlags = C.CL_MEM_USE_HOST_PTR
51 | MEM_ALLOC_HOST_PTR MemoryFlags = C.CL_MEM_ALLOC_HOST_PTR
52 | MEM_COPY_HOST_PTR MemoryFlags = C.CL_MEM_COPY_HOST_PTR
53 | )
54 |
55 | func releaseMemObject(p C.cl_mem) error {
56 | if p != nil {
57 | if err := C.clReleaseMemObject(p); err != C.CL_SUCCESS {
58 | return Cl_error(err)
59 | }
60 | }
61 | return nil
62 | }
63 |
--------------------------------------------------------------------------------
/cl/opencl.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I CL
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 | */
34 | import "C"
35 |
36 | import (
37 | "fmt"
38 | )
39 |
40 | var Platforms []Platform
41 |
42 | func init() {
43 | Platforms = GetPlatforms()
44 | }
45 |
46 | type Size C.size_t
47 |
48 | type Cl_error C.cl_int
49 |
50 | func (e Cl_error) Error() string {
51 | mesg := errMesg[e]
52 | if mesg == "" {
53 | return fmt.Sprintf("error %d", int(e))
54 | }
55 | return mesg
56 | }
57 |
58 | var errMesg = map[Cl_error]string{
59 | C.CL_SUCCESS: "Success",
60 |
61 | C.CL_BUILD_PROGRAM_FAILURE: "Build Program Failure",
62 | C.CL_COMPILER_NOT_AVAILABLE: "Compiler not Available",
63 | C.CL_DEVICE_NOT_AVAILABLE: "Device not Available",
64 | C.CL_DEVICE_NOT_FOUND: "Device not Found",
65 | C.CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST: "Wait List Event Error",
66 | C.CL_IMAGE_FORMAT_NOT_SUPPORTED: "Unsupported Image Format",
67 | C.CL_INVALID_BINARY: "Invalid Binary",
68 | C.CL_INVALID_BUFFER_SIZE: "Invalid Buffer Size",
69 | C.CL_INVALID_BUILD_OPTIONS: "Invalid Build Options",
70 | C.CL_INVALID_COMMAND_QUEUE: "Invalid Command Queue",
71 | C.CL_INVALID_CONTEXT: "Invalid Context",
72 | C.CL_INVALID_DEVICE: "Invalid Device",
73 | C.CL_INVALID_DEVICE_TYPE: "Invalid Device Type",
74 | C.CL_INVALID_EVENT_WAIT_LIST: "Invalid Event Wait List",
75 | C.CL_INVALID_GLOBAL_OFFSET: "Invalid Global Offset",
76 | C.CL_INVALID_GLOBAL_WORK_SIZE: "Invalid Global Work Size",
77 | C.CL_INVALID_HOST_PTR: "Invalid Host Pointer",
78 | C.CL_INVALID_IMAGE_FORMAT_DESCRIPTOR: "Invalid Image Format",
79 | C.CL_INVALID_IMAGE_SIZE: "Invalid Image Size",
80 | C.CL_INVALID_KERNEL: "Invalid Kernel",
81 | C.CL_INVALID_KERNEL_ARGS: "Invalid Kernel Arguments",
82 | C.CL_INVALID_KERNEL_DEFINITION: "Invalid Kernel Definition",
83 | C.CL_INVALID_KERNEL_NAME: "Invalid Kernel Name",
84 | C.CL_INVALID_MEM_OBJECT: "Invalid Memory Object",
85 | C.CL_INVALID_OPERATION: "Invalid Operation",
86 | C.CL_INVALID_PLATFORM: "Invalid Platform",
87 | C.CL_INVALID_PROPERTY: "Invalid Property",
88 | C.CL_INVALID_PROGRAM: "Invalid Program",
89 | C.CL_INVALID_PROGRAM_EXECUTABLE: "Invalid Program Executable",
90 | C.CL_INVALID_SAMPLER: "Invalid Sampler",
91 | C.CL_INVALID_VALUE: "Invalid Value",
92 | C.CL_INVALID_WORK_DIMENSION: "Invalid Work Dimension",
93 | C.CL_INVALID_WORK_GROUP_SIZE: "Invalid Work Group Size",
94 | C.CL_INVALID_WORK_ITEM_SIZE: "Invalid Work Item Size",
95 | C.CL_MEM_OBJECT_ALLOCATION_FAILURE: "Memory Object Allocation Failure",
96 | C.CL_MISALIGNED_SUB_BUFFER_OFFSET: "Misaligned Sub-Buffer Offset",
97 | C.CL_OUT_OF_HOST_MEMORY: "Out of Host Memory",
98 | C.CL_OUT_OF_RESOURCES: "Out of Resources",
99 | }
100 |
--------------------------------------------------------------------------------
/cl/opencl_test.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | import (
23 | "testing"
24 | )
25 |
26 | func getPlatform(t *testing.T) Platform {
27 | if len(Platforms) == 0 {
28 | t.Fatal("No platforms found")
29 | }
30 | return Platforms[0]
31 | }
32 |
33 | func getCPUDevice(p Platform, t *testing.T) []Device {
34 | if len(p.Devices) == 0 {
35 | t.Fatal("No devices found")
36 | }
37 | return p.Devices[:1]
38 | }
39 |
40 | func getContext(p Platform, d []Device, t *testing.T) *Context {
41 | if context, err := NewContextOfDevices(map[ContextParameter]interface{}{CONTEXT_PLATFORM: p}, d); err != nil {
42 | t.Fatal("Error creating context:", err)
43 | } else {
44 | return context
45 | }
46 | return nil
47 | }
48 |
49 | func getProgram(c *Context, filename string, t *testing.T) *Program {
50 | if program, err := c.NewProgramFromFile(filename); err != nil {
51 | t.Fatal("Error creating program:", err)
52 | } else {
53 | return program
54 | }
55 | return nil
56 | }
57 |
58 | func getKernel(p *Program, name string, t *testing.T) *Kernel {
59 | if kernel, err := p.NewKernelNamed(name); err != nil {
60 | t.Fatal("Error creating kernel:", err)
61 | } else {
62 | return kernel
63 | }
64 | return nil
65 | }
66 |
67 | func getQueue(c *Context, d Device, t *testing.T) *CommandQueue {
68 | if queue, err := c.NewCommandQueue(d, QUEUE_NIL); err != nil {
69 | t.Fatal("Error creating command queue:", err)
70 | } else {
71 | return queue
72 | }
73 | return nil
74 | }
75 |
76 | func Test_OpenCl(t *testing.T) {
77 | inData := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
78 |
79 | var err error
80 |
81 | platform := getPlatform(t)
82 | devices := getCPUDevice(platform, t)
83 | context := getContext(platform, devices, t)
84 | queue := getQueue(context, devices[0], t)
85 |
86 | program := getProgram(context, "vector.cl", t)
87 | if err = program.Build(nil, ""); err != nil {
88 | t.Fatal("Error building program:", err)
89 | }
90 | kernel := getKernel(program, "vectSquareUChar", t)
91 |
92 | var inBuf, outBuf *Buffer
93 | if inBuf, err = context.NewBuffer(MEM_READ_ONLY, 100); err != nil {
94 | t.Fatal("Error creating in buffer:", err)
95 | } else if outBuf, err = context.NewBuffer(MEM_WRITE_ONLY, 100); err != nil {
96 | t.Fatal("Error creating out buffer:", err)
97 | }
98 |
99 | if err = queue.EnqueueWriteBuffer(inBuf, inData, 0); err != nil {
100 | t.Fatal("Error enquing data:", err)
101 | }
102 |
103 | if err = kernel.SetArgs(0, []interface{}{inBuf, outBuf}); err != nil {
104 | t.Fatal("Error setting kernel arguments :", err)
105 | } else if err = queue.EnqueueKernel(kernel, []Size{0}, []Size{Size(len(inData))}, []Size{Size(len(inData))}); err != nil {
106 | t.Fatal("Error enquing kernel:", err)
107 | }
108 |
109 | var data []byte
110 | if data, err = queue.EnqueueReadBuffer(outBuf, 0, uint32(len(inData))); err != nil {
111 | t.Fatal("Error reading data:", err)
112 | }
113 |
114 | for i, v := range data {
115 | if v != inData[i]*inData[i] {
116 | t.Fatal("Incorrect results")
117 | }
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/cl/platform.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I CL
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 |
34 | */
35 | import "C"
36 |
37 | import (
38 | "unsafe"
39 | )
40 |
41 | type PlatformProperty C.cl_platform_info
42 |
43 | const (
44 | PLATFORM_PROFILE PlatformProperty = C.CL_PLATFORM_PROFILE
45 | PLATFORM_VERSION PlatformProperty = C.CL_PLATFORM_VERSION
46 | PLATFORM_NAME PlatformProperty = C.CL_PLATFORM_NAME
47 | PLATFORM_VENDOR PlatformProperty = C.CL_PLATFORM_VENDOR
48 | PLATFORM_EXTENSIONS PlatformProperty = C.CL_PLATFORM_EXTENSIONS
49 | )
50 |
51 | type Platform struct {
52 | id C.cl_platform_id
53 | Devices []Device
54 | properties map[PlatformProperty]string
55 | }
56 |
57 | func GetPlatforms() []Platform {
58 | var count C.cl_uint
59 | if ret := C.clGetPlatformIDs(0, (*C.cl_platform_id)(nil), &count); ret != C.CL_SUCCESS || count == 0 {
60 | return nil
61 | }
62 |
63 | c_platforms := make([]C.cl_platform_id, count)
64 | if ret := C.clGetPlatformIDs(count, &c_platforms[0], &count); ret != C.CL_SUCCESS || count == 0 {
65 | return nil
66 | }
67 | platforms := make([]Platform, 0, count)
68 |
69 | for _, pid := range c_platforms {
70 | if ret := C.clGetDeviceIDs(pid, C.cl_device_type(DEVICE_TYPE_ALL), 0, (*C.cl_device_id)(nil), &count); ret != C.CL_SUCCESS || count == 0 {
71 | continue
72 | }
73 |
74 | c_devices := make([]C.cl_device_id, count)
75 | if ret := C.clGetDeviceIDs(pid, C.cl_device_type(DEVICE_TYPE_ALL), count, &c_devices[0], &count); ret != C.CL_SUCCESS || count == 0 {
76 | continue
77 | }
78 |
79 | platform := Platform{
80 | id: pid,
81 | Devices: make([]Device, count),
82 | properties: make(map[PlatformProperty]string),
83 | }
84 | for i, did := range c_devices {
85 | platform.Devices[i].id = did
86 | platform.Devices[i].properties = make(map[DeviceProperty]interface{})
87 | }
88 | platforms = append(platforms, platform)
89 | }
90 | return platforms
91 | }
92 |
93 | func (p *Platform) Property(prop PlatformProperty) string {
94 | if value, ok := p.properties[prop]; ok {
95 | return value
96 | }
97 |
98 | var count C.size_t
99 | if ret := C.clGetPlatformInfo(p.id, C.cl_platform_info(prop), 0, nil, &count); ret != C.CL_SUCCESS || count < 1 {
100 | return ""
101 | }
102 |
103 | buf := make([]C.char, count)
104 | if ret := C.clGetPlatformInfo(p.id, C.cl_platform_info(prop), count, unsafe.Pointer(&buf[0]), &count); ret != C.CL_SUCCESS || count < 1 {
105 | return ""
106 | }
107 | p.properties[prop] = C.GoStringN(&buf[0], C.int(count-1))
108 | return p.properties[prop]
109 | }
110 |
--------------------------------------------------------------------------------
/cl/program.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I CL
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 | #include
34 |
35 | */
36 | import "C"
37 |
38 | import (
39 | "runtime"
40 | "unsafe"
41 | )
42 |
43 | type BuildProperty C.cl_program_build_info
44 |
45 | const (
46 | //BUILD_STATUS BuildProperty = C.CL_PROGRAM_BUILD_STATUS
47 | BUILD_OPTIONS BuildProperty = C.CL_PROGRAM_BUILD_OPTIONS
48 | BUILD_LOG BuildProperty = C.CL_PROGRAM_BUILD_LOG
49 | )
50 |
51 | type BuildStatus C.cl_build_status
52 |
53 | const (
54 | BUILD_NONE BuildStatus = C.CL_BUILD_NONE
55 | BUILD_ERROR BuildStatus = C.CL_BUILD_ERROR
56 | BUILD_SUCCESS BuildStatus = C.CL_BUILD_SUCCESS
57 | BUILD_IN_PROGRESS BuildStatus = C.CL_BUILD_IN_PROGRESS
58 | )
59 |
60 | func (status BuildStatus) String() string {
61 | switch status {
62 | case BUILD_NONE:
63 | return "None"
64 | case BUILD_ERROR:
65 | return "Error"
66 | case BUILD_SUCCESS:
67 | return "Success"
68 | case BUILD_IN_PROGRESS:
69 | return "In Progress"
70 | }
71 | return "Unknown"
72 | }
73 |
74 | type Program struct {
75 | id C.cl_program
76 | }
77 |
78 | func (p *Program) Build(devices []Device, options string) error {
79 | cs := C.CString(options)
80 | defer C.free(unsafe.Pointer(cs))
81 |
82 | if len(devices) < 1 {
83 | if ret := C.clBuildProgram(p.id, 0, nil, cs, nil, nil); ret != C.CL_SUCCESS {
84 | return Cl_error(ret)
85 | }
86 | return nil
87 | }
88 |
89 | c_devices := make([]C.cl_device_id, len(devices))
90 | for i, device := range devices {
91 | c_devices[i] = device.id
92 | }
93 | if ret := C.clBuildProgram(p.id, C.cl_uint(len(c_devices)), &c_devices[0], cs, nil, nil); ret != C.CL_SUCCESS {
94 | return Cl_error(ret)
95 | }
96 | return nil
97 | }
98 |
99 | func (p *Program) NewKernelNamed(name string) (*Kernel, error) {
100 | var c_kernel C.cl_kernel
101 | var err C.cl_int
102 |
103 | cs := C.CString(name)
104 | defer C.free(unsafe.Pointer(cs))
105 |
106 | if c_kernel = C.clCreateKernel(p.id, cs, &err); err != C.CL_SUCCESS {
107 | return nil, Cl_error(err)
108 | }
109 |
110 | kernel := &Kernel{id: c_kernel}
111 | runtime.SetFinalizer(kernel, (*Kernel).release)
112 |
113 | return kernel, nil
114 | }
115 |
116 | func (p *Program) BuildStatus(dev Device) BuildStatus {
117 | var c_status C.cl_build_status
118 | var count C.size_t
119 | if ret := C.clGetProgramBuildInfo(p.id, dev.id, C.CL_PROGRAM_BUILD_STATUS, C.size_t(unsafe.Sizeof(c_status)), unsafe.Pointer(&c_status), &count); ret != C.CL_SUCCESS {
120 | return BUILD_ERROR
121 | }
122 | return BuildStatus(c_status)
123 |
124 | }
125 |
126 | func (p *Program) Property(dev Device, prop BuildProperty) string {
127 | var count C.size_t
128 | if ret := C.clGetProgramBuildInfo(p.id, dev.id, C.cl_program_build_info(prop), 0, nil, &count); ret != C.CL_SUCCESS || count < 1 {
129 | return ""
130 | }
131 |
132 | buf := make([]C.char, count)
133 | if ret := C.clGetProgramBuildInfo(p.id, dev.id, C.cl_program_build_info(prop), count, unsafe.Pointer(&buf[0]), &count); ret != C.CL_SUCCESS || count < 1 {
134 | return ""
135 | }
136 | return C.GoStringN(&buf[0], C.int(count-1))
137 | }
138 |
139 | func (p *Program) release() error {
140 | if p.id != nil {
141 | if err := C.clReleaseProgram(p.id); err != C.CL_SUCCESS {
142 | return Cl_error(err)
143 | }
144 | p.id = nil
145 | }
146 | return nil
147 | }
148 |
--------------------------------------------------------------------------------
/cl/sampler.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | /*
23 | #cgo CFLAGS: -I .
24 | #cgo linux LDFLAGS: -lOpenCL
25 | #cgo windows LDFLAGS: -lOpenCL
26 | #cgo darwin LDFLAGS: -framework OpenCL
27 |
28 | #ifdef MAC
29 | #include "OpenCL/cl.h"
30 | #else
31 | #include "CL/opencl.h"
32 | #endif //MAC
33 |
34 | */
35 | import "C"
36 |
37 | import (
38 | "unsafe"
39 | )
40 |
41 | type AddressingMode C.cl_addressing_mode
42 |
43 | const (
44 | ADDRESS_NONE AddressingMode = C.CL_ADDRESS_NONE
45 | ADDRESS_CLAMP_TO_EDGE AddressingMode = C.CL_ADDRESS_CLAMP_TO_EDGE
46 | ADDRESS_CLAMP AddressingMode = C.CL_ADDRESS_CLAMP
47 | ADDRESS_REPEAT AddressingMode = C.CL_ADDRESS_REPEAT
48 | ADDRESS_MIRRORED_REPEAT AddressingMode = C.CL_ADDRESS_MIRRORED_REPEAT
49 | )
50 |
51 | type FilterMode C.cl_filter_mode
52 |
53 | const (
54 | FILTER_NEAREST FilterMode = C.CL_FILTER_NEAREST
55 | FILTER_LINEAR FilterMode = C.CL_FILTER_LINEAR
56 | )
57 |
58 | type SamplerProperty C.cl_sampler_info
59 |
60 | const (
61 | SAMPLER_REFERENCE_COUNT SamplerProperty = C.CL_SAMPLER_REFERENCE_COUNT
62 | //SAMPLER_CONTEXT SamplerProperty = C.CL_SAMPLER_CONTEXT
63 | SAMPLER_NORMALIZED_COORDS SamplerProperty = C.CL_SAMPLER_NORMALIZED_COORDS
64 | SAMPLER_ADDRESSING_MODE SamplerProperty = C.CL_SAMPLER_ADDRESSING_MODE
65 | SAMPLER_FILTER_MODE SamplerProperty = C.CL_SAMPLER_FILTER_MODE
66 | )
67 |
68 | type Sampler struct {
69 | id C.cl_sampler
70 | properties map[SamplerProperty]interface{}
71 | }
72 |
73 | func (s *Sampler) Property(prop SamplerProperty) interface{} {
74 | if value, ok := s.properties[prop]; ok {
75 | return value
76 | }
77 |
78 | var data interface{}
79 | var length C.size_t
80 | var ret C.cl_int
81 |
82 | switch prop {
83 | case SAMPLER_REFERENCE_COUNT:
84 | var val C.cl_uint
85 | ret = C.clGetSamplerInfo(s.id, C.cl_sampler_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
86 | data = val
87 | case SAMPLER_NORMALIZED_COORDS:
88 | var val C.cl_bool
89 | ret = C.clGetSamplerInfo(s.id, C.cl_sampler_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
90 | data = val == C.CL_TRUE
91 | case SAMPLER_ADDRESSING_MODE:
92 | var val C.cl_addressing_mode
93 | ret = C.clGetSamplerInfo(s.id, C.cl_sampler_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
94 | data = AddressingMode(ret)
95 | case SAMPLER_FILTER_MODE:
96 | var val C.cl_filter_mode
97 | ret = C.clGetSamplerInfo(s.id, C.cl_sampler_info(prop), C.size_t(unsafe.Sizeof(val)), unsafe.Pointer(&val), &length)
98 | data = FilterMode(ret)
99 | default:
100 | return nil
101 | }
102 |
103 | if ret != C.CL_SUCCESS {
104 | return nil
105 | }
106 | s.properties[prop] = data
107 | return s.properties[prop]
108 | }
109 |
110 | func (s *Sampler) release() error {
111 | if s.id != nil {
112 | if err := C.clReleaseSampler(C.cl_sampler(s.id)); err != C.CL_SUCCESS {
113 | return Cl_error(err)
114 | }
115 | }
116 | return nil
117 | }
118 |
--------------------------------------------------------------------------------
/cl/vectAdd_test.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 go-opencl authors
3 | *
4 | * This file is part of go-opencl.
5 | *
6 | * go-opencl is free software: you can redistribute it and/or modify
7 | * it under the terms of the GNU Lesser General Public License as published by
8 | * the Free Software Foundation, either version 3 of the License, or
9 | * (at your option) any later version.
10 | *
11 | * go-opencl is distributed in the hope that it will be useful,
12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | * GNU Lesser General Public License for more details.
15 | *
16 | * You should have received a copy of the GNU Lesser General Public License
17 | * along with go-opencl. If not, see .
18 | */
19 |
20 | package cl
21 |
22 | import (
23 | "github.com/pseudomind/go-opencl/raw"
24 | "testing"
25 | )
26 |
27 | func Test_VectAdd(t *testing.T) {
28 | const elements = 100000
29 |
30 | A := make([]int, elements)
31 | B := make([]int, elements)
32 | for i := 0; i < elements; i++ {
33 | A[i], B[i] = i, i
34 | }
35 | bytes := uint32(len(raw.ByteSlice(A)))
36 |
37 | for _, platform := range Platforms {
38 | for _, dev := range platform.Devices {
39 |
40 | var err error
41 | var context *Context
42 | var queue *CommandQueue
43 | var bufA, bufB, bufC *Buffer
44 | var program *Program
45 | var kernel *Kernel
46 |
47 | if context, err = NewContextOfDevices(nil, []Device{dev}); err != nil {
48 | t.Fatal(err)
49 | }
50 |
51 | if queue, err = context.NewCommandQueue(dev, QUEUE_NIL); err != nil {
52 | t.Fatal(err)
53 | }
54 |
55 | if bufA, err = context.NewBuffer(MEM_READ_ONLY, bytes); err != nil {
56 | t.Fatal(err)
57 | }
58 | if bufB, err = context.NewBuffer(MEM_READ_ONLY, bytes); err != nil {
59 | t.Fatal(err)
60 | }
61 | if bufC, err = context.NewBuffer(MEM_WRITE_ONLY, bytes); err != nil {
62 | t.Fatal(err)
63 | }
64 |
65 | if err = queue.EnqueueWriteBuffer(bufA, raw.ByteSlice(A), 0); err != nil {
66 | t.Fatal(err)
67 | }
68 | if err = queue.EnqueueWriteBuffer(bufB, raw.ByteSlice(B), 0); err != nil {
69 | t.Fatal(err)
70 | }
71 |
72 | if program, err = context.NewProgramFromFile("vector.cl"); err != nil {
73 | t.Fatal(err)
74 | }
75 |
76 | if err = program.Build([]Device{dev}, ""); err != nil {
77 | t.Fatal(err)
78 | }
79 |
80 | if kernel, err = program.NewKernelNamed("vectAddInt"); err != nil {
81 | t.Fatal(err)
82 | }
83 |
84 | if err = kernel.SetArgs(0, []interface{}{bufA, bufB, bufC}); err != nil {
85 | t.Fatal(err)
86 | }
87 |
88 | if err = queue.EnqueueKernel(kernel, []Size{0}, []Size{elements}, []Size{1}); err != nil {
89 | t.Fatal(err)
90 | }
91 |
92 | if outBuf, err := queue.EnqueueReadBuffer(bufC, 0, bytes); err != nil {
93 | t.Fatal(err)
94 | } else {
95 | C := raw.IntSlice(outBuf)
96 |
97 | for i := 0; i < elements; i++ {
98 | if C[i] != i<<1 {
99 | t.Fatal("Output is incorrect")
100 | }
101 | }
102 | }
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/cl/vector.cl:
--------------------------------------------------------------------------------
1 | __kernel void vectAddInt(__global int *A,
2 | __global int *B,
3 | __global int *C)
4 | {
5 | int i = get_global_id(0);
6 | C[i] = A[i] + B[i];
7 | }
8 |
9 | __kernel void vectSquareUChar(__global uchar *input,
10 | __global uchar *output)
11 | {
12 | size_t id = get_global_id(0);
13 | output[id] = input[id] * input[id];
14 | }
15 |
--------------------------------------------------------------------------------
/examples/clinfo/clinfo.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 Paul Sbarra
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License as published by
6 | * the Free Software Foundation, either version 3 of the License, or
7 | * (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package main
19 |
20 | import (
21 | "fmt"
22 | "github.com/pseudomind/go-opencl/cl"
23 | )
24 |
25 | func main() {
26 | fmt.Println("Number of Platforms:", len(cl.Platforms))
27 | for _, platform := range cl.Platforms {
28 | fmt.Println(" Platform Profile:", platform.Property(cl.PLATFORM_PROFILE))
29 | fmt.Println(" Platform Version:", platform.Property(cl.PLATFORM_VERSION))
30 | fmt.Println(" Platform Name:", platform.Property(cl.PLATFORM_NAME))
31 | fmt.Println(" Platform Vendor:", platform.Property(cl.PLATFORM_VENDOR))
32 | fmt.Printf(" Platform Extensions: %v\n\n", platform.Property(cl.PLATFORM_EXTENSIONS))
33 | fmt.Println(" Platform Name:", platform.Property(cl.PLATFORM_NAME))
34 |
35 | fmt.Println("Number of devices:", len(platform.Devices))
36 | for _, device := range platform.Devices {
37 | fmt.Println(" Device Type:", device.Property(cl.DEVICE_TYPE))
38 | //fmt.Println(" Device ID:", "TODO")
39 | //fmt.Println(" Board name:", "TODO")
40 | fmt.Println(" Max compute units:", device.Property(cl.DEVICE_MAX_COMPUTE_UNITS))
41 | fmt.Println(" Max work items dimensions:", device.Property(cl.DEVICE_MAX_WORK_ITEM_DIMENSIONS))
42 | //fmt.Println(" Max work items[]", "TODO")
43 | fmt.Println(" Max work group size:", device.Property(cl.DEVICE_MAX_WORK_GROUP_SIZE))
44 | fmt.Println(" Preferred vector width char:", device.Property(cl.DEVICE_PREFERRED_VECTOR_WIDTH_CHAR))
45 | fmt.Println(" Preferred vector width short:", device.Property(cl.DEVICE_PREFERRED_VECTOR_WIDTH_SHORT))
46 | fmt.Println(" Preferred vector width int:", device.Property(cl.DEVICE_PREFERRED_VECTOR_WIDTH_INT))
47 | fmt.Println(" Preferred vector width long:", device.Property(cl.DEVICE_PREFERRED_VECTOR_WIDTH_LONG))
48 | fmt.Println(" Preferred vector width float:", device.Property(cl.DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT))
49 | fmt.Println(" Preferred vector width double:", device.Property(cl.DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE))
50 | fmt.Println(" Native vector width char:", device.Property(cl.DEVICE_NATIVE_VECTOR_WIDTH_CHAR))
51 | fmt.Println(" Native vector width short:", device.Property(cl.DEVICE_NATIVE_VECTOR_WIDTH_SHORT))
52 | fmt.Println(" Native vector width int:", device.Property(cl.DEVICE_NATIVE_VECTOR_WIDTH_INT))
53 | fmt.Println(" Native vector width long:", device.Property(cl.DEVICE_NATIVE_VECTOR_WIDTH_LONG))
54 | fmt.Println(" Native vector width float:", device.Property(cl.DEVICE_NATIVE_VECTOR_WIDTH_FLOAT))
55 | fmt.Println(" Native vector width double:", device.Property(cl.DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE))
56 | fmt.Printf(" Max clock frequency: %dMhz\n", device.Property(cl.DEVICE_MAX_CLOCK_FREQUENCY))
57 | fmt.Println(" Address bits:", device.Property(cl.DEVICE_ADDRESS_BITS))
58 | fmt.Println(" Max memory allocation:", device.Property(cl.DEVICE_MAX_MEM_ALLOC_SIZE))
59 | fmt.Println(" Image support:", device.Property(cl.DEVICE_IMAGE_SUPPORT))
60 | fmt.Println(" Max number of images read arguments:", device.Property(cl.DEVICE_MAX_READ_IMAGE_ARGS))
61 | fmt.Println(" Max number of images write arguments:", device.Property(cl.DEVICE_MAX_WRITE_IMAGE_ARGS))
62 | fmt.Println(" Max image 2D width:", device.Property(cl.DEVICE_IMAGE2D_MAX_WIDTH))
63 | fmt.Println(" Max image 2D height:", device.Property(cl.DEVICE_IMAGE2D_MAX_HEIGHT))
64 | fmt.Println(" Max image 3D width:", device.Property(cl.DEVICE_IMAGE3D_MAX_WIDTH))
65 | fmt.Println(" Max image 3D height:", device.Property(cl.DEVICE_IMAGE3D_MAX_HEIGHT))
66 | fmt.Println(" Max image 3D depth:", device.Property(cl.DEVICE_IMAGE3D_MAX_DEPTH))
67 | fmt.Println(" Max samplers within kernel:", device.Property(cl.DEVICE_MAX_SAMPLERS))
68 | fmt.Println(" Max size of kernel argument:", device.Property(cl.DEVICE_MAX_PARAMETER_SIZE))
69 | fmt.Println(" Alignment (bits) of base address:", device.Property(cl.DEVICE_MEM_BASE_ADDR_ALIGN))
70 | fmt.Println(" Minimum alignment (bytes) for any datatype:", device.Property(cl.DEVICE_MIN_DATA_TYPE_ALIGN_SIZE))
71 |
72 | /*fmt.Println(" Single precision floating point capability")
73 | fmt.Println(" Denorms:", "TODO")
74 | fmt.Println(" Quiet NaNs:", "TODO")
75 | fmt.Println(" Round to nearest even:", "TODO")
76 | fmt.Println(" Round to zero:", "TODO")
77 | fmt.Println(" Round to +ve and infinity:", "TODO")
78 | fmt.Println(" IEEE754-2008 fused multiply-add:", "TODO")
79 | */
80 |
81 | //fmt.Println(" Cache type:", "TODO" /*device.Property(cl.DEVICE_GLOBAL_MEM_CACHE_TYPE)*/ )
82 | //fmt.Println(" Cache line size:", "TODO" /*device.Property(cl.DEVICE_GLOBAL_MEM_CACHELINE_SIZE)*/ )
83 | fmt.Println(" Cache size:", device.Property(cl.DEVICE_GLOBAL_MEM_CACHE_SIZE))
84 | fmt.Println(" Global memory size:", device.Property(cl.DEVICE_GLOBAL_MEM_SIZE))
85 | fmt.Println(" Constant buffer size:", device.Property(cl.DEVICE_MAX_CONSTANT_BUFFER_SIZE))
86 | fmt.Println(" Max number of constant args:", device.Property(cl.DEVICE_MAX_CONSTANT_ARGS))
87 |
88 | //fmt.Println(" Local memory type:", "TODO" /*device.Property(cl.DEVICE_LOCAL_MEM_TYPE)*/ )
89 | fmt.Println(" Local memory size:", device.Property(cl.DEVICE_LOCAL_MEM_SIZE))
90 | //fmt.Println(" Kernel Preferred work group size multiple:", "TODO")
91 | fmt.Println(" Error correction support:", device.Property(cl.DEVICE_ERROR_CORRECTION_SUPPORT))
92 | fmt.Println(" Unified memory for Host and Device:", device.Property(cl.DEVICE_HOST_UNIFIED_MEMORY))
93 | fmt.Println(" Profiling timer resolution:", device.Property(cl.DEVICE_PROFILING_TIMER_RESOLUTION))
94 | fmt.Println(" Little endian:", device.Property(cl.DEVICE_ENDIAN_LITTLE))
95 | fmt.Println(" Available:", device.Property(cl.DEVICE_AVAILABLE))
96 | fmt.Println(" Compiler available:", device.Property(cl.DEVICE_COMPILER_AVAILABLE))
97 |
98 | /*fmt.Println(" Execution capabilities:")
99 | fmt.Println(" Execute OpenCL kernels:", "TODO")
100 | fmt.Println(" Execute native function:", "TODO")
101 | */
102 |
103 | /*fmt.Println(" Queue properties:")
104 | fmt.Println(" Out-of-Order:", "TODO")
105 | fmt.Println(" Profiling:", "TODO")
106 | */
107 |
108 | //fmt.Println(" Platform ID:", "TODO" /* device.Property(cl.DEVICE_PLATFORM)*/ )
109 | fmt.Println(" Name:", device.Property(cl.DEVICE_NAME))
110 | fmt.Println(" Vendor:", device.Property(cl.DEVICE_VENDOR))
111 | fmt.Println(" Device OpenCL C version:", device.Property(cl.DEVICE_OPENCL_C_VERSION))
112 | fmt.Println(" Driver version:", device.Property(cl.DRIVER_VERSION))
113 | fmt.Println(" Profile:", device.Property(cl.DEVICE_PROFILE))
114 | fmt.Println(" Version:", device.Property(cl.DEVICE_VERSION))
115 | fmt.Println(" Extensions:", device.Property(cl.DEVICE_EXTENSIONS))
116 | }
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/examples/rotate/rotate.cl:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 Paul Sbarra
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License as published by
6 | * the Free Software Foundation, either version 3 of the License, or
7 | * (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | __kernel void imageRotate(__read_only image2d_t sourceImage,
19 | __write_only image2d_t destImage,
20 | float sinTheta,
21 | float cosTheta,
22 | sampler_t sampler)
23 | {
24 | int2 srcCoords, destCoords;
25 |
26 | const int2 center = {get_image_width(sourceImage) / 2, get_image_height(sourceImage) / 2};
27 |
28 | destCoords.x = get_global_id(0);
29 | destCoords.y = get_global_id(1);
30 |
31 | srcCoords.x = (float)(destCoords.x - center.x) * cosTheta + (float)(destCoords.y - center.y) * sinTheta + center.x;
32 | srcCoords.y = (float)(destCoords.y - center.y) * cosTheta - (float)(destCoords.x - center.x) * sinTheta + center.y;
33 |
34 | write_imageui(destImage, destCoords, read_imageui(sourceImage, sampler, srcCoords));
35 | }
36 |
--------------------------------------------------------------------------------
/examples/rotate/rotate.go:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright © 2012 Paul Sbarra
3 | *
4 | * This program is free software: you can redistribute it and/or modify
5 | * it under the terms of the GNU General Public License as published by
6 | * the Free Software Foundation, either version 3 of the License, or
7 | * (at your option) any later version.
8 | *
9 | * This program is distributed in the hope that it will be useful,
10 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | * GNU General Public License for more details.
13 | *
14 | * You should have received a copy of the GNU General Public License
15 | * along with this program. If not, see .
16 | */
17 |
18 | package main
19 |
20 | import (
21 | "flag"
22 | "fmt"
23 | "github.com/pseudomind/go-opencl/cl"
24 | "github.com/pseudomind/go-opencl/raw"
25 | "image"
26 | "image/jpeg"
27 | "image/png"
28 | "io"
29 | "math"
30 | "os"
31 | )
32 |
33 | var (
34 | angle *float64 = flag.Float64("a", 0, "Rotation Angle, CW (Degrees)")
35 | inFilename *string = flag.String("i", "", "Input Filename")
36 | outFilename *string = flag.String("o", "", "Output Filename")
37 | help *bool = flag.Bool("h", false, "Display Usage")
38 | )
39 |
40 | type customError struct {
41 | mesg string
42 | }
43 |
44 | func (e *customError) Error() string {
45 | return e.mesg
46 | }
47 |
48 | func init() {
49 | flag.Parse()
50 | }
51 |
52 | func fatalError(err error) {
53 | fmt.Fprintf(os.Stderr, "Error: %v\n", err)
54 | os.Exit(1)
55 | }
56 |
57 | func imagePixels(img image.Image) ([]uint32, error) {
58 | bounds := img.Bounds()
59 | size := bounds.Size()
60 | if size.X <= 0 || size.Y <= 0 {
61 | return nil, &customError{fmt.Sprint("Invalid image size: ", size)}
62 | }
63 |
64 | pixels := make([]uint32, 4*size.X*size.Y)
65 | index := 0
66 | for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
67 | for x := bounds.Min.X; x < bounds.Max.X; x++ {
68 | pixels[index], pixels[index+1], pixels[index+2], pixels[index+3] = img.At(x, y).RGBA()
69 | index += 4
70 | }
71 | }
72 | return pixels, nil
73 | }
74 |
75 | func main() {
76 | var err error
77 |
78 | if *help {
79 | fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
80 | flag.PrintDefaults()
81 | return
82 | }
83 |
84 | var input io.Reader
85 | if len(*inFilename) == 0 {
86 | input = os.Stdin
87 | } else {
88 | if input, err = os.Open(*inFilename); err != nil {
89 | fatalError(err)
90 | }
91 | }
92 |
93 | var output io.Writer
94 | if len(*outFilename) == 0 {
95 | output = os.Stdout
96 | } else {
97 | if output, err = os.Create(*outFilename); err != nil {
98 | fatalError(err)
99 | }
100 | }
101 |
102 | var inImage image.Image
103 | var inFormat string
104 | if inImage, inFormat, err = image.Decode(input); err != nil {
105 | fatalError(err)
106 | }
107 |
108 | size := inImage.Bounds().Size()
109 | var pixels []uint32
110 | if pixels, err = imagePixels(inImage); err != nil {
111 | fatalError(err)
112 | }
113 | _ = pixels
114 |
115 | for _, platform := range cl.Platforms {
116 | for _, dev := range platform.Devices {
117 | var context *cl.Context
118 | var queue *cl.CommandQueue
119 | var sourceImage, destImage *cl.Image
120 | var sampler *cl.Sampler
121 | var program *cl.Program
122 | var kernel *cl.Kernel
123 | var outPixels []byte
124 |
125 | if context, err = cl.NewContextOfDevices(map[cl.ContextParameter]interface{}{cl.CONTEXT_PLATFORM: platform}, []cl.Device{dev}); err != nil {
126 | fatalError(err)
127 | }
128 |
129 | format := cl.ImageFormat{ChannelOrder: cl.RGBA, ChannelDataType: cl.UNSIGNED_INT32}
130 | if sourceImage, err = context.NewImage2D(cl.MEM_READ_ONLY, format, uint32(size.X), uint32(size.Y), 0, nil); err != nil {
131 | fatalError(err)
132 | }
133 |
134 | if destImage, err = context.NewImage2D(cl.MEM_WRITE_ONLY, format, uint32(size.X), uint32(size.Y), 0, nil); err != nil {
135 | fatalError(err)
136 | }
137 |
138 | if sampler, err = context.NewSampler(false, cl.ADDRESS_CLAMP, cl.FILTER_NEAREST); err != nil {
139 | fatalError(err)
140 | }
141 |
142 | if queue, err = context.NewCommandQueue(dev, cl.QUEUE_NIL); err != nil {
143 | fatalError(err)
144 | }
145 |
146 | if program, err = context.NewProgramFromFile("rotate.cl"); err != nil {
147 | fatalError(err)
148 | }
149 |
150 | if err = program.Build(nil, ""); err != nil {
151 | if status := program.BuildStatus(dev); status != cl.BUILD_SUCCESS {
152 | fatalError(&customError{fmt.Sprintf("Build Error:\n%s\n", program.Property(dev, cl.BUILD_LOG))})
153 | }
154 | fatalError(err)
155 | }
156 |
157 | if kernel, err = program.NewKernelNamed("imageRotate"); err != nil {
158 | fatalError(err)
159 | }
160 |
161 | if err = queue.EnqueueWriteImage(sourceImage, true, [3]cl.Size{0, 0, 0}, [3]cl.Size{cl.Size(size.X), cl.Size(size.Y), 1}, 0, 0, raw.ByteSlice(pixels)); err != nil {
162 | fatalError(err)
163 | }
164 |
165 | if err = kernel.SetArgs(0, []interface{}{
166 | sourceImage, destImage,
167 | float32(math.Sin(*angle * math.Pi / 180)),
168 | float32(math.Cos(*angle * math.Pi / 180)),
169 | sampler}); err != nil {
170 | fatalError(err)
171 | }
172 |
173 | if err = queue.EnqueueKernel(kernel, []cl.Size{0, 0, 0}, []cl.Size{cl.Size(size.X), cl.Size(size.Y), 1}, []cl.Size{1, 1, 1}); err != nil {
174 | fatalError(err)
175 | }
176 |
177 | if outPixels, err = queue.EnqueueReadImage(destImage, true, [3]cl.Size{0, 0, 0}, [3]cl.Size{cl.Size(size.X), cl.Size(size.Y), 1}, 0, 0); err != nil {
178 | fatalError(err)
179 | }
180 |
181 | outImage := image.NewNRGBA(inImage.Bounds())
182 | for i := 0; i < len(outImage.Pix); i++ {
183 | outImage.Pix[i] = uint8(outPixels[4*i])
184 | }
185 |
186 | switch inFormat {
187 | case "jpeg":
188 | if err = jpeg.Encode(output, outImage, nil); err != nil {
189 | fatalError(err)
190 | }
191 | case "png":
192 | if err = png.Encode(output, outImage); err != nil {
193 | fatalError(err)
194 | }
195 | default:
196 | fatalError(&customError{fmt.Sprintf("Unknown Format: %s", inFormat)})
197 | }
198 | return
199 | }
200 | }
201 |
202 | }
203 |
--------------------------------------------------------------------------------
/raw/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2011 Eleanor McHugh
2 |
3 | Permission is hereby granted, free of charge, to any person
4 | obtaining a copy of this software and associated documentation
5 | files (the "Software"), to deal in the Software without
6 | restriction, including without limitation the rights to use,
7 | copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | copies of the Software, and to permit persons to whom the
9 | Software is furnished to do so, subject to the following
10 | conditions:
11 |
12 | The above copyright notice and this permission notice shall be
13 | included in all copies or substantial portions of the Software.
14 |
15 | The Software shall be used for Good, not Evil.
16 |
17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 | NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
22 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
24 | OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
/raw/README:
--------------------------------------------------------------------------------
1 | == Disclaimer ==
2 | The RAW package circumvents and subverts Go's type system. As such it should be used with extreme caution and only
3 | when absolutely necessary. Incautious use can and will lead to memory corruption. As such no warranty can be provided
4 | as to its suitability or fitness for purpose.
5 |
6 | Just to reiterate: MISUSE WILL RESULT IN MEMORY CORRUPTION.
7 |
8 |
9 | == License ==
10 |
11 | RAW is dual-licensed.
12 |
13 | The library can be included in your project as "Random Access Woe" under the BSD-derived license in LICENSE.
14 |
15 | "Read it And Weep" is the closed-source variant of the library. It is in all particulars identical to the open-source
16 | version but requires a commercial usage license and in the process hides your shame for abusing Go in this manner.
17 | Further details of commercial license costs are available from the author on request.
18 |
19 |
20 | == About ==
21 |
22 | RAW is a high-level interface to Go's unsafe and reflection packages, designed to ease both generic programming and
23 | low-level memory access.
24 |
25 | RAW allows any type with identifiable contiguous memory allocation to be converted to a byte slice which can then
26 | be manipulated using many of the standard IO interfaces provided by the core library. This is very unsafe but for
27 | certain system programming tasks can be very useful. In particular it facilitates the sharing of memory buffers with
28 | language runtimes and any number of related tricks such as polymorphic variables, mixed-content arrays and binary
29 | data marshalling.
30 |
31 | Documentation is currently sparse but will improve over time. I have tried to keep nomenclature clear to assist with
32 | figuring our how the library should be used and there are also extensive tests which demonstrate all of the library
33 | types and their methods in use.
34 |
35 |
36 | == History ==
37 |
38 | The RAW package began life as a research spike of the GoLightly virtual machine project and was originally to be called
39 | either "Dangerous" or "Deadly" to reflect the unpleasant consequences of misuse. A friend suggested "Random Access Woe"
40 | and the name stuck.
--------------------------------------------------------------------------------
/raw/byte_slice.go:
--------------------------------------------------------------------------------
1 | // Originally cloned from `github.com/tones111/raw`
2 | //
3 | // Copyright (c) 2011 Eleanor McHugh
4 | //
5 | // For addtional deatils, see the included `LICENSE` file
6 |
7 | package raw
8 |
9 | // THIS SHOULD BE IN A SEPARATE PACKAGE WHERE IT CAN BE REUSED MORE EASILY
10 | // THE PACKAGE SHOULD BE INSTALLABLE VIA GOINSTALL
11 | // AND NEEDS EXTENSIVE TESTS!!!!
12 |
13 | import (
14 | "reflect"
15 | "unsafe"
16 | )
17 |
18 | var _BYTE_SLICE reflect.Type
19 | var _STRING reflect.Type
20 |
21 | func init() {
22 | _BYTE_SLICE = reflect.TypeOf([]byte(nil))
23 | _STRING = reflect.TypeOf("")
24 | }
25 |
26 | /*
27 | A Buffered object can present itself as a byteslice.
28 | This byteslice can then be manipulated directly to modify the contents of memory.
29 | Use with extreme caution.
30 | */
31 | type MemoryBlock interface {
32 | ByteSlice() []byte
33 | }
34 |
35 | func ByteSlice(i interface{}) []byte {
36 | /*
37 | A byteslice is by definition its own buffer.
38 | Any type which implements the Buffer interface will generate its result using that method.
39 | */
40 | switch b := i.(type) {
41 | case []byte:
42 | return b
43 | case MemoryBlock:
44 | return b.ByteSlice()
45 | case nil:
46 | return []byte{}
47 | }
48 |
49 | /*
50 | For nil values we return a buffer to a zero-capacity byte slice.
51 | There are cerain types which cannot be cast as a buffer and instead raise a panic.
52 | In the rare case of the interface itself containing another interface we recursively query.
53 | When given a pointer we use its target address and the size of the type it points to construct a SliceHeader.
54 | For SliceValues we can do a simple conversion of the SliceHeader to a byteslice.
55 | For StringValues we treat them as a fixed capacity byte slice.
56 | */
57 | var header *reflect.SliceHeader
58 |
59 | switch value := reflect.ValueOf(i); value.Kind() {
60 | case reflect.Slice:
61 | h, s, _ := SliceHeader(i)
62 | header = Scale(h, s, 1)
63 |
64 | case reflect.String:
65 | s := value.String()
66 | stringheader := *(*reflect.StringHeader)(unsafe.Pointer(&s))
67 | header = &reflect.SliceHeader{stringheader.Data, stringheader.Len, stringheader.Len}
68 |
69 | case reflect.Interface, reflect.Ptr:
70 | header = valueHeader(value.Elem())
71 |
72 | default: // For every other type the value gives us an address for the data
73 | // Given this and the size of the underlying allocated memory we can
74 | // then create a []byte sliceheader and return a valid slice
75 | header = valueHeader(value)
76 | }
77 |
78 | bs := reflect.NewAt(_BYTE_SLICE, unsafe.Pointer(header))
79 | if !bs.Elem().IsValid() {
80 | return []byte{}
81 | }
82 | return bs.Elem().Interface().([]byte)
83 | }
84 |
85 | func valueHeader(v reflect.Value) (h *reflect.SliceHeader) {
86 | if v.IsValid() {
87 | size := int(v.Type().Size())
88 | h = &reflect.SliceHeader{v.UnsafeAddr(), size, size}
89 | }
90 | return
91 | }
92 |
93 | func DataAddress(b []byte) (p unsafe.Pointer) {
94 | defer func() {
95 | if r := recover(); r != nil {
96 | p = unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&b)).Data)
97 | }
98 | }()
99 | return unsafe.Pointer(&(b[0]))
100 | }
101 |
102 | func ByteCopy(d interface{}, s interface{}) {
103 | db := ByteSlice(d)
104 | sb := ByteSlice(s)
105 | copy(db, sb)
106 |
107 | dh, element_size, _ := SliceHeader(d)
108 | dh.Len = len(db) / element_size
109 | dh.Cap = cap(db) / element_size
110 | }
111 |
--------------------------------------------------------------------------------
/raw/byte_slice_test.go:
--------------------------------------------------------------------------------
1 | // Originally cloned from `github.com/tones111/raw`
2 | //
3 | // Copyright (c) 2011 Eleanor McHugh
4 | //
5 | // For addtional deatils, see the included `LICENSE` file
6 |
7 | package raw
8 |
9 | import (
10 | "reflect"
11 | "testing"
12 | "unsafe"
13 | )
14 |
15 | func TestByteSliceWithNil(t *testing.T) {
16 | b := ByteSlice(nil)
17 | buf := ByteSlice(b)
18 | if len(buf) != 0 {
19 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), 0)
20 | }
21 | if cap(buf) != cap(b) {
22 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), 0)
23 | }
24 |
25 | sliceheader := *(*reflect.SliceHeader)(unsafe.Pointer(&b))
26 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
27 | if sliceheader.Data != bufheader.Data {
28 | t.Fatalf("slice addresses don't match: %v != %v", sliceheader.Data, bufheader.Data)
29 | }
30 | }
31 |
32 | func TestByteSliceWithByteSlice(t *testing.T) {
33 | b := make([]byte, 10, 10)
34 | buf := ByteSlice(b)
35 | if len(buf) != len(b) {
36 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), len(b))
37 | }
38 | if cap(buf) != cap(b) {
39 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), cap(b))
40 | }
41 |
42 | sliceheader := *(*reflect.SliceHeader)(unsafe.Pointer(&b))
43 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
44 | if sliceheader.Data != bufheader.Data {
45 | t.Fatalf("slice addresses don't match: %v != %v", sliceheader.Data, bufheader.Data)
46 | }
47 | }
48 |
49 | func TestByteSliceWithMap(t *testing.T) {
50 | m := make(map[int]int)
51 | defer func() {
52 | if x := recover(); x == nil {
53 | t.Fatalf("should have raised a panic")
54 | }
55 | }()
56 | ByteSlice(m)
57 | }
58 |
59 | func TestByteSliceWithChannel(t *testing.T) {
60 | c := make(chan int)
61 | defer func() {
62 | if x := recover(); x == nil {
63 | t.Fatalf("should have raised a panic")
64 | }
65 | }()
66 | ByteSlice(c)
67 | }
68 |
69 | func TestByteSliceWithInterface(t *testing.T) {
70 | t.Log("Awaiting bug fix for incorrect reporting of interface{} value size with unsafe.Sizeof()")
71 | /* var i interface{} = make([]byte, INTERFACE.size, INTERFACE.size)
72 | b := i.([]byte)
73 | buf := ByteSlice(i)
74 | if len(buf) != len(b) {
75 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), len(b))
76 | }
77 | if cap(buf) != cap(b) {
78 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), cap(b))
79 | }
80 |
81 | sliceheader := *(*reflect.SliceHeader)(unsafe.Pointer(&b))
82 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
83 | if sliceheader.Data != bufheader.Data {
84 | t.Fatalf("slice addresses don't match: %v != %v", sliceheader.Data, bufheader.Data)
85 | }
86 | */
87 | }
88 |
89 | func TestByteSliceWithString(t *testing.T) {
90 | s := "hello"
91 | buf := ByteSlice(s)
92 | if len(buf) != len(s) {
93 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), len(s))
94 | }
95 | if cap(buf) != len(s) {
96 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), len(s))
97 | }
98 |
99 | stringheader := *(*reflect.StringHeader)(unsafe.Pointer(&s))
100 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
101 | if stringheader.Data != bufheader.Data {
102 | t.Fatalf("slice addresses don't match: %v != %v", stringheader.Data, bufheader.Data)
103 | }
104 | }
105 |
106 | type Point struct {
107 | x int32
108 | y int32
109 | z int32
110 | }
111 |
112 | func TestByteSliceWithStructValue(t *testing.T) {
113 | point := Point{3, 4, 5}
114 | buf := ByteSlice(&point)
115 |
116 | size := int(unsafe.Sizeof(point))
117 | if len(buf) != size {
118 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), size)
119 | }
120 |
121 | if cap(buf) != size {
122 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), size)
123 | }
124 |
125 | base_address := uintptr(unsafe.Pointer(&point))
126 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
127 | if base_address != bufheader.Data {
128 | t.Fatalf("slice addresses don't match: %v != %v", base_address, bufheader.Data)
129 | }
130 | }
131 |
132 | func TestByteSliceWithStructPointer(t *testing.T) {
133 | point := &Point{3, 4, 5}
134 | buf := ByteSlice(point)
135 |
136 | size := int(unsafe.Sizeof(*point))
137 | if len(buf) != size {
138 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), size)
139 | }
140 |
141 | if cap(buf) != size {
142 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), size)
143 | }
144 |
145 | base_address := uintptr(unsafe.Pointer(point))
146 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
147 | if base_address != bufheader.Data {
148 | t.Fatalf("slice addresses don't match: %v != %v", base_address, bufheader.Data)
149 | }
150 | }
151 |
152 | type TaggedPoint struct {
153 | Point
154 | tag string
155 | }
156 |
157 | func TestByteSliceWithEmbeddedStructValue(t *testing.T) {
158 | point := Point{3, 4, 5}
159 | tag := &TaggedPoint{point, "this is a tag"}
160 | buf := ByteSlice(tag)
161 |
162 | size := int(unsafe.Sizeof(*tag))
163 | if len(buf) != size {
164 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), size)
165 | }
166 |
167 | if cap(buf) != size {
168 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), size)
169 | }
170 |
171 | base_address := uintptr(unsafe.Pointer(tag))
172 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
173 | if base_address != bufheader.Data {
174 | t.Fatalf("slice addresses don't match: %v != %v", base_address, bufheader.Data)
175 | }
176 | }
177 |
178 | type TaggedPointReference struct {
179 | *Point
180 | tag string
181 | }
182 |
183 | func TestByteSliceWithEmbeddedStructPointer(t *testing.T) {
184 | point := Point{3, 4, 5}
185 | tag := &TaggedPointReference{&point, "this is a tag"}
186 | buf := ByteSlice(tag)
187 |
188 | size := int(unsafe.Sizeof(*tag))
189 | if len(buf) != size {
190 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), size)
191 | }
192 |
193 | if cap(buf) != size {
194 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), size)
195 | }
196 |
197 | base_address := uintptr(unsafe.Pointer(tag))
198 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
199 | if base_address != bufheader.Data {
200 | t.Fatalf("slice addresses don't match: %v != %v", base_address, bufheader.Data)
201 | }
202 | }
203 |
204 | func TestByteSliceWithInt32Slice(t *testing.T) {
205 | i := make([]int32, 10, 10)
206 | buf := ByteSlice(i)
207 | size := len(i) * INT32.size
208 | if len(buf) != size {
209 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), size)
210 | }
211 |
212 | if cap(buf) != size {
213 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), size)
214 | }
215 |
216 | sliceheader := *(*reflect.SliceHeader)(unsafe.Pointer(&i))
217 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
218 | if sliceheader.Data != bufheader.Data {
219 | t.Fatalf("slice addresses don't match: %v != %v", sliceheader.Data, bufheader.Data)
220 | }
221 | }
222 |
223 | func TestByteSliceWithInt64Slice(t *testing.T) {
224 | i := make([]int64, 10, 10)
225 | buf := ByteSlice(i)
226 | size := len(i) * INT64.size
227 | if len(buf) != size {
228 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), size)
229 | }
230 |
231 | if cap(buf) != size {
232 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), size)
233 | }
234 |
235 | sliceheader := *(*reflect.SliceHeader)(unsafe.Pointer(&i))
236 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
237 | if sliceheader.Data != bufheader.Data {
238 | t.Fatalf("slice addresses don't match: %v != %v", sliceheader.Data, bufheader.Data)
239 | }
240 | }
241 |
242 | func TestByteSliceWithFloat32Slice(t *testing.T) {
243 | f := make([]float32, 10, 10)
244 | buf := ByteSlice(f)
245 | size := len(f) * FLOAT32.size
246 | if len(buf) != size {
247 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), size)
248 | }
249 |
250 | if cap(buf) != size {
251 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), size)
252 | }
253 |
254 | sliceheader := *(*reflect.SliceHeader)(unsafe.Pointer(&f))
255 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
256 | if sliceheader.Data != bufheader.Data {
257 | t.Fatalf("slice addresses don't match: %v != %v", sliceheader.Data, bufheader.Data)
258 | }
259 | }
260 |
261 | func TestByteSliceWithFloat64Slice(t *testing.T) {
262 | f := make([]float64, 10, 10)
263 | buf := ByteSlice(f)
264 | size := len(f) * FLOAT64.size
265 | if len(buf) != size {
266 | t.Fatalf("byte buffer lengths differ: %v != %v", len(buf), size)
267 | }
268 |
269 | if cap(buf) != size {
270 | t.Fatalf("byte buffer capacities differ: %v != %v", cap(buf), size)
271 | }
272 |
273 | sliceheader := *(*reflect.SliceHeader)(unsafe.Pointer(&f))
274 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
275 | if sliceheader.Data != bufheader.Data {
276 | t.Fatalf("slice addresses don't match: %v != %v", sliceheader.Data, bufheader.Data)
277 | }
278 | }
279 |
280 | func ValidateNumericByteSlice(t *testing.T, value interface{}) {
281 | var size int
282 | var addr uintptr
283 | var numtype reflect.Type
284 |
285 | v := reflect.ValueOf(value)
286 | if v.Kind() == reflect.Ptr {
287 | v = v.Elem()
288 | }
289 | size = int(v.Type().Size())
290 | addr = v.UnsafeAddr()
291 | numtype = v.Type()
292 |
293 | buf := ByteSlice(value)
294 | if len(buf) != size {
295 | t.Fatalf("%v: byte buffer lengths differ: %v != %v", numtype, len(buf), size)
296 | }
297 |
298 | if cap(buf) != size {
299 | t.Fatalf("%v: byte buffer capacities differ: %v != %v", numtype, cap(buf), size)
300 | }
301 |
302 | bufheader := *(*reflect.SliceHeader)(unsafe.Pointer(&buf))
303 | if addr != bufheader.Data {
304 | t.Fatalf("%v: addresses don't match: %v != %v", numtype, addr, bufheader.Data)
305 | }
306 | }
307 |
308 | func TestByteSliceWithNumbers(t *testing.T) {
309 | var i int
310 | var i8 int8
311 | var i16 int16
312 | var i32 int32
313 | var i64 int64
314 | var u uint
315 | var u8 uint8
316 | var u16 uint16
317 | var u32 uint32
318 | var u64 uint64
319 | var f32 float32
320 | var f64 float64
321 | var c64 complex64
322 | var c128 complex64
323 |
324 | ValidateNumericByteSlice(t, &i)
325 | ValidateNumericByteSlice(t, &i8)
326 | ValidateNumericByteSlice(t, &i16)
327 | ValidateNumericByteSlice(t, &i32)
328 | ValidateNumericByteSlice(t, &i64)
329 | ValidateNumericByteSlice(t, &u)
330 | ValidateNumericByteSlice(t, &u8)
331 | ValidateNumericByteSlice(t, &u16)
332 | ValidateNumericByteSlice(t, &u32)
333 | ValidateNumericByteSlice(t, &u64)
334 | ValidateNumericByteSlice(t, &f32)
335 | ValidateNumericByteSlice(t, &f64)
336 | ValidateNumericByteSlice(t, &c64)
337 | ValidateNumericByteSlice(t, &c128)
338 | }
339 |
340 | func TestByteSliceWithNumbersInSlice(t *testing.T) {
341 | values := []interface{}{int(0), int8(0), int16(0), int32(0), int64(0),
342 | uint(0), uint8(0), uint16(0), uint32(0), uint64(0),
343 | float32(0.0), float64(0.0),
344 | complex64(0), complex128(0)}
345 | for i, _ := range values {
346 | ValidateNumericByteSlice(t, &values[i])
347 | }
348 | }
349 |
350 | func TestByteSliceDataAddress(t *testing.T) {
351 | DataAddress([]byte{})
352 | DataAddress(make([]byte, 0, 0))
353 | }
354 |
355 | func TestSliceByteCopy(t *testing.T) {
356 | s := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
357 | for i := 0; i < len(s); i++ {
358 | c := cap(s) / 2
359 | if c < i {
360 | c = i
361 | }
362 | d := make([]int, i, c)
363 | ByteCopy(d, s)
364 | if len(d) != i {
365 | t.Fatalf("destination buffer length changed: %v != %v", len(d), i)
366 | }
367 | if !reflect.DeepEqual(d, s[:i]) {
368 | t.Fatalf("buffer contents differ: %v != %v", d, s[:i])
369 | }
370 | }
371 | }
372 |
--------------------------------------------------------------------------------
/raw/reslice.go:
--------------------------------------------------------------------------------
1 | // Originally cloned from `github.com/tones111/raw`
2 | //
3 | // Copyright (c) 2011 Eleanor McHugh
4 | //
5 | // For addtional deatils, see the included `LICENSE` file
6 |
7 | package raw
8 |
9 | import (
10 | "reflect"
11 | "unsafe"
12 | )
13 |
14 | func sliceHeaderFromValue(v reflect.Value) (s *reflect.SliceHeader) {
15 | switch v.Kind() {
16 | case reflect.Slice:
17 | if !v.CanAddr() {
18 | x := reflect.New(v.Type()).Elem()
19 | x.Set(v)
20 | v = x
21 | }
22 | s = (*reflect.SliceHeader)(unsafe.Pointer(v.UnsafeAddr()))
23 | case reflect.Ptr, reflect.Interface:
24 | s = sliceHeaderFromValue(v.Elem())
25 | }
26 | return
27 | }
28 |
29 | func SliceHeader(i interface{}) (Header *reflect.SliceHeader, ElementSize, ElementAlignment int) {
30 | value := reflect.ValueOf(i)
31 | if Header = sliceHeaderFromValue(value); Header != nil {
32 | ElementType := value.Type().Elem()
33 | ElementSize = int(ElementType.Size())
34 | ElementAlignment = int(ElementType.Align())
35 | } else {
36 | panic(i)
37 | }
38 | return
39 | }
40 |
41 | func Scale(oldHeader *reflect.SliceHeader, oldElementSize, newElementSize int) (h *reflect.SliceHeader) {
42 | if oldHeader != nil {
43 | s := float64(oldElementSize) / float64(newElementSize)
44 | h = &reflect.SliceHeader{Data: oldHeader.Data}
45 | h.Len = int(float64(oldHeader.Len) * s)
46 | h.Cap = int(float64(oldHeader.Cap) * s)
47 | }
48 | return
49 | }
50 |
51 | func Reslice(slice interface{}, sliceType reflect.Type, elementSize int) interface{} {
52 | b := ByteSlice(slice)
53 | h := Scale(&reflect.SliceHeader{uintptr(DataAddress(b)), len(b), cap(b)}, 1, elementSize)
54 | return reflect.NewAt(sliceType, unsafe.Pointer(h)).Elem().Interface()
55 | }
56 |
57 | func PointerSlice(i interface{}) []unsafe.Pointer {
58 | return Reslice(i, POINTER.slice_type, POINTER.size).([]unsafe.Pointer)
59 | }
60 |
61 | func UintptrSlice(i interface{}) []uintptr {
62 | return Reslice(i, UINTPTR.slice_type, UINTPTR.size).([]uintptr)
63 | }
64 |
65 | func InterfaceSlice(i interface{}) []interface{} {
66 | return Reslice(i, INTERFACE.slice_type, INTERFACE.size).([]interface{})
67 | }
68 |
69 | func BoolSlice(i interface{}) []bool {
70 | return Reslice(i, BOOLEAN.slice_type, BOOLEAN.size).([]bool)
71 | }
72 |
73 | func IntSlice(i interface{}) []int {
74 | if i, ok := i.([]uint); ok {
75 | return *(*[]int)(unsafe.Pointer(&i))
76 | }
77 | return Reslice(i, INT.slice_type, INT.size).([]int)
78 | }
79 |
80 | func Int8Slice(i interface{}) []int8 {
81 | if i, ok := i.([]uint8); ok {
82 | return *(*[]int8)(unsafe.Pointer(&i))
83 | }
84 | return Reslice(i, INT8.slice_type, INT8.size).([]int8)
85 | }
86 |
87 | func Int16Slice(i interface{}) []int16 {
88 | if i, ok := i.([]uint16); ok {
89 | return *(*[]int16)(unsafe.Pointer(&i))
90 | }
91 | return Reslice(i, INT16.slice_type, INT16.size).([]int16)
92 | }
93 |
94 | func Int32Slice(i interface{}) []int32 {
95 | switch i := i.(type) {
96 | case []uint32:
97 | return *(*[]int32)(unsafe.Pointer(&i))
98 | case []float32:
99 | return *(*[]int32)(unsafe.Pointer(&i))
100 | }
101 | return Reslice(i, INT32.slice_type, INT32.size).([]int32)
102 | }
103 |
104 | func Int64Slice(i interface{}) []int64 {
105 | switch i := i.(type) {
106 | case []uint64:
107 | return *(*[]int64)(unsafe.Pointer(&i))
108 | case []float64:
109 | return *(*[]int64)(unsafe.Pointer(&i))
110 | }
111 | return Reslice(i, INT64.slice_type, INT64.size).([]int64)
112 | }
113 |
114 | func UintSlice(i interface{}) []uint {
115 | if i, ok := i.([]int); ok {
116 | return *(*[]uint)(unsafe.Pointer(&i))
117 | }
118 | return Reslice(i, UINT.slice_type, UINT.size).([]uint)
119 | }
120 |
121 | func Uint8Slice(i interface{}) []uint8 {
122 | if i, ok := i.([]int8); ok {
123 | return *(*[]uint8)(unsafe.Pointer(&i))
124 | }
125 | return Reslice(i, UINT8.slice_type, UINT8.size).([]uint8)
126 | }
127 |
128 | func Uint16Slice(i interface{}) []uint16 {
129 | if i, ok := i.([]int16); ok {
130 | return *(*[]uint16)(unsafe.Pointer(&i))
131 | }
132 | return Reslice(i, UINT16.slice_type, UINT16.size).([]uint16)
133 | }
134 |
135 | func Uint32Slice(i interface{}) []uint32 {
136 | switch i := i.(type) {
137 | case []int32:
138 | return *(*[]uint32)(unsafe.Pointer(&i))
139 | case []float32:
140 | return *(*[]uint32)(unsafe.Pointer(&i))
141 | }
142 | return Reslice(i, UINT32.slice_type, UINT32.size).([]uint32)
143 | }
144 |
145 | func Uint64Slice(i interface{}) []uint64 {
146 | switch i := i.(type) {
147 | case []int64:
148 | return *(*[]uint64)(unsafe.Pointer(&i))
149 | case []float64:
150 | return *(*[]uint64)(unsafe.Pointer(&i))
151 | }
152 | return Reslice(i, UINT64.slice_type, UINT64.size).([]uint64)
153 | }
154 |
155 | func Float32Slice(i interface{}) []float32 {
156 | switch i := i.(type) {
157 | case []int32:
158 | return *(*[]float32)(unsafe.Pointer(&i))
159 | case []uint32:
160 | return *(*[]float32)(unsafe.Pointer(&i))
161 | }
162 | return Reslice(i, FLOAT32.slice_type, FLOAT32.size).([]float32)
163 | }
164 |
165 | func Float64Slice(i interface{}) []float64 {
166 | switch i := i.(type) {
167 | case []int64:
168 | return *(*[]float64)(unsafe.Pointer(&i))
169 | case []uint64:
170 | return *(*[]float64)(unsafe.Pointer(&i))
171 | case []complex64:
172 | return *(*[]float64)(unsafe.Pointer(&i))
173 | }
174 | return Reslice(i, FLOAT64.slice_type, FLOAT64.size).([]float64)
175 | }
176 |
177 | func Complex64Slice(i interface{}) []complex64 {
178 | switch i := i.(type) {
179 | case []int64:
180 | return *(*[]complex64)(unsafe.Pointer(&i))
181 | case []uint64:
182 | return *(*[]complex64)(unsafe.Pointer(&i))
183 | case []float64:
184 | return *(*[]complex64)(unsafe.Pointer(&i))
185 | }
186 | return Reslice(i, COMPLEX64.slice_type, COMPLEX64.size).([]complex64)
187 | }
188 |
189 | func Complex128Slice(i interface{}) []complex128 {
190 | return Reslice(i, COMPLEX128.slice_type, COMPLEX128.size).([]complex128)
191 | }
192 |
--------------------------------------------------------------------------------
/raw/reslice_test.go:
--------------------------------------------------------------------------------
1 | // Originally cloned from `github.com/tones111/raw`
2 | //
3 | // Copyright (c) 2011 Eleanor McHugh
4 | //
5 | // For addtional deatils, see the included `LICENSE` file
6 |
7 | package raw
8 |
9 | import (
10 | "fmt"
11 | "reflect"
12 | "testing"
13 | "unsafe"
14 | )
15 |
16 | type HeaderMismatch struct {
17 | message string
18 | x, y, z interface{}
19 | }
20 |
21 | func (h HeaderMismatch) Error() string {
22 | return fmt.Sprintf(h.message, h.x, h.y, h.z)
23 | }
24 |
25 | func MatchHeaders(b BasicType, slice interface{}, header reflect.SliceHeader) (e error) {
26 | h, s, al := SliceHeader(slice)
27 | switch {
28 | case s != b.size:
29 | e = HeaderMismatch{"%v: slice element size should be %v not %v", b.name, b.size, s}
30 | case al != b.alignment:
31 | e = HeaderMismatch{"%v: slice element alignment should be %v not %v", b.name, b.alignment, al}
32 | case h.Data != header.Data:
33 | e = HeaderMismatch{"%v: slice headers should point to the same memory: %v - %v", b.name, h.Data, header.Data}
34 | case h.Len != header.Len:
35 | e = HeaderMismatch{"%v: slice header lengths should be the same: %v - %v", b.name, h.Len, header.Len}
36 | case h.Cap != header.Cap:
37 | e = HeaderMismatch{"%v: slice header capacities should be the same: %v - %v", b.name, h.Cap, header.Cap}
38 | }
39 | return
40 | }
41 |
42 | func TestSliceHeaderByte(t *testing.T) {
43 | slice := []byte{0, 1, 2, 3, 4, 5}
44 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
45 | if m := MatchHeaders(BYTE, slice, header); m != nil {
46 | t.Fatal(m)
47 | }
48 | }
49 |
50 | func TestSliceHeaderPointer(t *testing.T) {
51 | a, b, c, d, e, f := 0, 1, 2, 3, 4, 5
52 | slice := []unsafe.Pointer{unsafe.Pointer(&a), unsafe.Pointer(&b), unsafe.Pointer(&c), unsafe.Pointer(&d), unsafe.Pointer(&e), unsafe.Pointer(&f)}
53 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
54 | if m := MatchHeaders(POINTER, slice, header); m != nil {
55 | t.Fatal(m)
56 | }
57 | }
58 |
59 | func TestSliceHeaderUintptr(t *testing.T) {
60 | slice := []uintptr{0, 1, 2, 3, 4, 5}
61 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
62 | if m := MatchHeaders(UINTPTR, slice, header); m != nil {
63 | t.Fatal(m)
64 | }
65 | }
66 |
67 | func TestSliceHeaderInterface(t *testing.T) {
68 | t.Log("Awaiting bug fix for incorrect reporting of interface{} value size with unsafe.Sizeof()")
69 | /*
70 | slice := []interface{}{ 0, 1, 2, 3, 4, 5 }
71 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
72 | if m := MatchHeaders(INTERFACE, slice, header); m != nil {
73 | t.Fatal(m)
74 | }
75 | */
76 | }
77 |
78 | func TestSliceHeaderBool(t *testing.T) {
79 | slice := []bool{true, false, true, false, false, true}
80 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
81 | if m := MatchHeaders(BOOLEAN, slice, header); m != nil {
82 | t.Fatal(m)
83 | }
84 | }
85 |
86 | func TestSliceHeaderUint(t *testing.T) {
87 | slice := []uint{0, 1, 2, 3, 4, 5}
88 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
89 | if m := MatchHeaders(UINT, slice, header); m != nil {
90 | t.Fatal(m)
91 | }
92 | }
93 |
94 | func TestSliceHeaderUint8(t *testing.T) {
95 | slice := []uint8{0, 1, 2, 3, 4, 5}
96 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
97 | if m := MatchHeaders(UINT8, slice, header); m != nil {
98 | t.Fatal(m)
99 | }
100 | }
101 |
102 | func TestSliceHeaderUint16(t *testing.T) {
103 | slice := []uint16{0, 1, 2, 3, 4, 5}
104 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
105 | if m := MatchHeaders(UINT16, slice, header); m != nil {
106 | t.Fatal(m)
107 | }
108 | }
109 |
110 | func TestSliceHeaderUint32(t *testing.T) {
111 | slice := []uint32{0, 1, 2, 3, 4, 5}
112 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
113 | if m := MatchHeaders(UINT32, slice, header); m != nil {
114 | t.Fatal(m)
115 | }
116 | }
117 |
118 | func TestSliceHeaderInt(t *testing.T) {
119 | slice := []int{0, 1, 2, 3, 4, 5}
120 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
121 | if m := MatchHeaders(INT, slice, header); m != nil {
122 | t.Fatal(m)
123 | }
124 | }
125 |
126 | func TestSliceHeaderInt8(t *testing.T) {
127 | slice := []int8{0, 1, 2, 3, 4, 5}
128 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
129 | if m := MatchHeaders(INT8, slice, header); m != nil {
130 | t.Fatal(m)
131 | }
132 | }
133 |
134 | func TestSliceHeaderInt16(t *testing.T) {
135 | slice := []int16{0, 1, 2, 3, 4, 5}
136 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
137 | if m := MatchHeaders(INT16, slice, header); m != nil {
138 | t.Fatal(m)
139 | }
140 | }
141 |
142 | func TestSliceHeaderInt32(t *testing.T) {
143 | slice := []int32{0, 1, 2, 3, 4, 5}
144 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
145 | if m := MatchHeaders(INT32, slice, header); m != nil {
146 | t.Fatal(m)
147 | }
148 | }
149 |
150 | func TestSliceHeaderFloat32(t *testing.T) {
151 | slice := []float32{0.0, 1.0, 2.0, 3.0, 4.0, 5.0}
152 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
153 | if m := MatchHeaders(FLOAT32, slice, header); m != nil {
154 | t.Fatal(m)
155 | }
156 | }
157 |
158 | func TestSliceHeaderFloat64(t *testing.T) {
159 | slice := []float64{0.0, 1.0, 2.0, 3.0, 4.0, 5.0}
160 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
161 | if m := MatchHeaders(FLOAT64, slice, header); m != nil {
162 | t.Fatal(m)
163 | }
164 | }
165 |
166 | func TestSliceHeaderComplex64(t *testing.T) {
167 | slice := []complex64{0, 0, 0, 0, 0, 0}
168 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
169 | if m := MatchHeaders(COMPLEX64, slice, header); m != nil {
170 | t.Fatal(m)
171 | }
172 | }
173 |
174 | func TestSliceHeaderComplex128(t *testing.T) {
175 | slice := []complex128{0, 0, 0, 0, 0, 0}
176 | header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))
177 | if m := MatchHeaders(COMPLEX128, slice, header); m != nil {
178 | t.Fatal(m)
179 | }
180 | }
181 |
182 | func TestScale(t *testing.T) {
183 | var h *reflect.SliceHeader
184 |
185 | if Scale(h, 0, 0) != nil {
186 | t.Fatal("Scaling a nil *SliceHeader should return a nil *SliceHeader")
187 | }
188 |
189 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
190 | h, _, _ = SliceHeader(b)
191 | hs := Scale(h, 1, 2)
192 | switch {
193 | case hs.Len != h.Len/2:
194 | t.Fatalf("new slice length should be %v not %v", h.Len/2, hs.Len)
195 | case hs.Cap != h.Cap/2:
196 | t.Fatalf("new slice capacity should be %v not %v", h.Cap/2, hs.Cap)
197 | }
198 |
199 | i32 := []int32{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
200 | h, _, _ = SliceHeader(i32)
201 | hs = Scale(h, INT32.size, BYTE.size)
202 | switch {
203 | case hs.Len != h.Len*INT32.size/BYTE.size:
204 | t.Fatalf("new slice length should be %v not %v", h.Len*INT32.size/BYTE.size, hs.Len)
205 | case hs.Cap != h.Cap*INT32.size/BYTE.size:
206 | t.Fatalf("new slice capacity should be %v not %v", h.Cap*INT32.size/BYTE.size, hs.Cap)
207 | }
208 | }
209 |
210 | func TestResliceNil(t *testing.T) {
211 | var h *reflect.SliceHeader
212 |
213 | hs := &reflect.SliceHeader{}
214 | h, _, _ = SliceHeader(Reslice(h, INT32.slice_type, INT32.size))
215 | switch {
216 | case h.Len != hs.Len:
217 | t.Fatalf("SliceHeader reslice length should be %v not %v", h.Len, hs.Len)
218 | case h.Cap != hs.Cap:
219 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", h.Cap, hs.Cap)
220 | }
221 | }
222 |
223 | func TestReslice(t *testing.T) {
224 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
225 | h, _, _ := SliceHeader(b)
226 | h, _, _ = SliceHeader(Reslice(h, INT32.slice_type, INT32.size))
227 | switch {
228 | case h.Len != len(b)/4:
229 | t.Fatalf("SliceHeader reslice length should be %v not %v", h.Len, len(b)/4)
230 | case h.Cap != cap(b)/4:
231 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", h.Cap, cap(b)/4)
232 | }
233 | }
234 |
235 | func TestPointerSlice(t *testing.T) {
236 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
237 | p := PointerSlice(b)
238 | switch {
239 | case len(p) != len(b)/POINTER.size:
240 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/POINTER.size)
241 | case len(p) != cap(b)/POINTER.size:
242 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/POINTER.size)
243 | }
244 | }
245 |
246 | func TestUintptrSlice(t *testing.T) {
247 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
248 | p := UintptrSlice(b)
249 | switch {
250 | case len(p) != len(b)/UINTPTR.size:
251 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/UINTPTR.size)
252 | case len(p) != cap(b)/UINTPTR.size:
253 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/UINTPTR.size)
254 | }
255 | }
256 |
257 | func TestInterfaceSlice(t *testing.T) {
258 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
259 | p := InterfaceSlice(b)
260 | switch {
261 | case len(p) != len(b)/INTERFACE.size:
262 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/INTERFACE.size)
263 | case len(p) != cap(b)/INTERFACE.size:
264 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/INTERFACE.size)
265 | }
266 | }
267 |
268 | func TestBoolSlice(t *testing.T) {
269 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
270 | p := BoolSlice(b)
271 | switch {
272 | case len(p) != len(b)/BOOLEAN.size:
273 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/BOOLEAN.size)
274 | case len(p) != cap(b)/BOOLEAN.size:
275 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/BOOLEAN.size)
276 | }
277 | }
278 |
279 | func TestIntSlice(t *testing.T) {
280 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
281 | p := IntSlice(b)
282 | switch {
283 | case len(p) != len(b)/INT.size:
284 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/INT.size)
285 | case len(p) != cap(b)/INT.size:
286 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/INT.size)
287 | }
288 | }
289 |
290 | func TestInt8Slice(t *testing.T) {
291 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
292 | p := Int8Slice(b)
293 | switch {
294 | case len(p) != len(b)/INT8.size:
295 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/INT8.size)
296 | case len(p) != cap(b)/INT8.size:
297 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/INT8.size)
298 | }
299 | }
300 |
301 | func TestInt16Slice(t *testing.T) {
302 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
303 | p := Int16Slice(b)
304 | switch {
305 | case len(p) != len(b)/INT16.size:
306 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/INT16.size)
307 | case len(p) != cap(b)/INT16.size:
308 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/INT16.size)
309 | }
310 | }
311 |
312 | func TestInt32Slice(t *testing.T) {
313 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
314 | p := Int32Slice(b)
315 | switch {
316 | case len(p) != len(b)/INT32.size:
317 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/INT32.size)
318 | case len(p) != cap(b)/INT32.size:
319 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/INT32.size)
320 | }
321 | }
322 |
323 | func TestInt64Slice(t *testing.T) {
324 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
325 | p := Int64Slice(b)
326 | switch {
327 | case len(p) != len(b)/INT64.size:
328 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/INT64.size)
329 | case len(p) != cap(b)/INT64.size:
330 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/INT64.size)
331 | }
332 | }
333 |
334 | func TestUintSlice(t *testing.T) {
335 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
336 | p := UintSlice(b)
337 | switch {
338 | case len(p) != len(b)/UINT.size:
339 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/UINT.size)
340 | case len(p) != cap(b)/UINT.size:
341 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/UINT.size)
342 | }
343 | }
344 |
345 | func TestUint8Slice(t *testing.T) {
346 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
347 | p := Uint8Slice(b)
348 | switch {
349 | case len(p) != len(b)/UINT8.size:
350 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/UINT8.size)
351 | case len(p) != cap(b)/UINT8.size:
352 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/UINT8.size)
353 | }
354 | }
355 |
356 | func TestUint16Slice(t *testing.T) {
357 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
358 | p := Uint16Slice(b)
359 | switch {
360 | case len(p) != len(b)/UINT16.size:
361 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/UINT16.size)
362 | case len(p) != cap(b)/UINT16.size:
363 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/UINT16.size)
364 | }
365 | }
366 |
367 | func TestUint32Slice(t *testing.T) {
368 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
369 | p := Uint32Slice(b)
370 | switch {
371 | case len(p) != len(b)/UINT32.size:
372 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/UINT32.size)
373 | case len(p) != cap(b)/UINT32.size:
374 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/UINT32.size)
375 | }
376 | }
377 |
378 | func TestUint64Slice(t *testing.T) {
379 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
380 | p := Uint64Slice(b)
381 | switch {
382 | case len(p) != len(b)/UINT64.size:
383 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/UINT64.size)
384 | case len(p) != cap(b)/UINT64.size:
385 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/UINT64.size)
386 | }
387 | }
388 |
389 | func TestFloat32Slice(t *testing.T) {
390 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
391 | p := Float32Slice(b)
392 | switch {
393 | case len(p) != len(b)/FLOAT32.size:
394 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/FLOAT32.size)
395 | case len(p) != cap(b)/FLOAT32.size:
396 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/FLOAT32.size)
397 | }
398 | }
399 |
400 | func TestFloat64Slice(t *testing.T) {
401 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
402 | p := Float64Slice(b)
403 | switch {
404 | case len(p) != len(b)/FLOAT64.size:
405 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/FLOAT64.size)
406 | case len(p) != cap(b)/FLOAT64.size:
407 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/FLOAT64.size)
408 | }
409 | }
410 |
411 | func TestComplex64Slice(t *testing.T) {
412 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
413 | p := Complex64Slice(b)
414 | switch {
415 | case len(p) != len(b)/COMPLEX64.size:
416 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/COMPLEX64.size)
417 | case len(p) != cap(b)/COMPLEX64.size:
418 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/COMPLEX64.size)
419 | }
420 | }
421 |
422 | func TestComplex128Slice(t *testing.T) {
423 | b := []byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
424 | p := Complex128Slice(b)
425 | switch {
426 | case len(p) != len(b)/COMPLEX128.size:
427 | t.Fatalf("SliceHeader reslice length should be %v not %v", len(p), len(b)/COMPLEX128.size)
428 | case len(p) != cap(b)/COMPLEX128.size:
429 | t.Fatalf("SliceHeader reslice capacity should be %v not %v", cap(p), cap(b)/COMPLEX128.size)
430 | }
431 | }
432 |
--------------------------------------------------------------------------------
/raw/runtime.go:
--------------------------------------------------------------------------------
1 | // Originally cloned from `github.com/tones111/raw`
2 | //
3 | // Copyright (c) 2011 Eleanor McHugh
4 | //
5 | // For addtional deatils, see the included `LICENSE` file
6 |
7 | package raw
8 |
9 | func Throw() {
10 | panic(nil)
11 | }
12 |
13 | func Catch(f func()) {
14 | defer func() {
15 | if x := recover(); x != nil {
16 | panic(x)
17 | }
18 | }()
19 | f()
20 | }
21 |
22 | func CatchAll(f func()) {
23 | defer func() {
24 | recover()
25 | }()
26 | f()
27 | }
28 |
--------------------------------------------------------------------------------
/raw/runtime_test.go:
--------------------------------------------------------------------------------
1 | // Originally cloned from `github.com/tones111/raw`
2 | //
3 | // Copyright (c) 2011 Eleanor McHugh
4 | //
5 | // For addtional deatils, see the included `LICENSE` file
6 |
7 | package raw
8 |
9 | import "testing"
10 |
11 | func TestThrow(t *testing.T) {}
12 |
13 | func TestCatch(t *testing.T) {}
14 |
15 | func TestCatchAll(t *testing.T) {}
16 |
--------------------------------------------------------------------------------
/raw/type.go:
--------------------------------------------------------------------------------
1 | // Originally cloned from `github.com/tones111/raw`
2 | //
3 | // Copyright (c) 2011 Eleanor McHugh
4 | //
5 | // For addtional deatils, see the included `LICENSE` file
6 |
7 | package raw
8 |
9 | import (
10 | "fmt"
11 | "reflect"
12 | "unsafe"
13 | )
14 |
15 | func ConcreteValue(value interface{}) (r reflect.Value) {
16 | for r = reflect.ValueOf(value); r.Kind() == reflect.Ptr; r = reflect.Indirect(r) {
17 | }
18 | return
19 | }
20 |
21 | func MakeAddressable(value reflect.Value) reflect.Value {
22 | if !value.CanAddr() {
23 | ptr := reflect.New(value.Type()).Elem()
24 | ptr.Set(value)
25 | value = ptr
26 | }
27 | return value
28 | }
29 |
30 | func Assign(location, value reflect.Value) {
31 | location = MakeAddressable(location)
32 | location.Set(value)
33 | }
34 |
35 | type Typed interface {
36 | Type() reflect.Type
37 | }
38 |
39 | func Type(v interface{}) (r reflect.Type) {
40 | switch v := v.(type) {
41 | case Typed:
42 | r = v.Type()
43 | default:
44 | r = reflect.TypeOf(v)
45 | }
46 | return
47 | }
48 |
49 | func Compatible(l, r interface{}) (b bool) {
50 | CatchAll(func() {
51 | l, r := Type(l), Type(r)
52 | switch {
53 | case l.Kind() == reflect.Chan && r.Kind() == reflect.Chan:
54 | b = l.Elem() == r.Elem() && l.ChanDir() == r.ChanDir()
55 | case l.Kind() == reflect.Chan, r.Kind() == reflect.Chan:
56 | b = l.Elem() == r.Elem()
57 | case l.Kind() == reflect.Map && r.Kind() == reflect.Map:
58 | b = l.Elem() == r.Elem() && l.Key() == r.Key()
59 | case l.Kind() == reflect.Map:
60 | b = l.Key() == Type(INT) && l.Elem() == r.Elem()
61 | case r.Kind() == reflect.Map:
62 | b = r.Key() == Type(INT) && l.Elem() == r.Elem()
63 | default:
64 | b = l.Elem() == r.Elem()
65 | }
66 | })
67 | return
68 | }
69 |
70 | func RegisterType(name string, v, s interface{}) (r BasicType) {
71 | r.name = name
72 | r._type = reflect.TypeOf(v)
73 | r.size = int(r._type.Size())
74 | r.alignment = int(r._type.Align())
75 | r.slice_type = reflect.TypeOf(s)
76 | return
77 | }
78 |
79 | type BasicType struct {
80 | _type reflect.Type
81 | name string
82 | size int
83 | alignment int
84 | slice_type reflect.Type
85 | }
86 |
87 | func (b BasicType) Type() reflect.Type {
88 | return b._type
89 | }
90 |
91 | func (b BasicType) String() string {
92 | return fmt.Sprintf("%v: %v bytes aligned at %v byte", b.name, b.size, b.alignment)
93 | }
94 |
95 | var _a interface{} = 0
96 |
97 | var POINTER = RegisterType("unsafe.Pointer", unsafe.Pointer(&_a), []unsafe.Pointer{})
98 | var UINTPTR = RegisterType("uintptr", uintptr(0), []uintptr{})
99 | var INTERFACE = RegisterType("interface{}", _a, []interface{}{})
100 | var BOOLEAN = RegisterType("bool", true, []bool{})
101 | var BYTE = RegisterType("byte", byte(0), []byte{})
102 | var INT = RegisterType("int", int(0), []int{})
103 | var INT8 = RegisterType("int8", int8(0), []int8{})
104 | var INT16 = RegisterType("int16", int16(0), []int16{})
105 | var INT32 = RegisterType("int32", int32(0), []int32{})
106 | var INT64 = RegisterType("int64", int64(0), []int64{})
107 | var UINT = RegisterType("uint", uint(0), []uint{})
108 | var UINT8 = RegisterType("uint8", uint8(0), []uint8{})
109 | var UINT16 = RegisterType("uint16", uint16(0), []uint16{})
110 | var UINT32 = RegisterType("uint32", uint32(0), []uint32{})
111 | var UINT64 = RegisterType("uint64", uint64(0), []uint64{})
112 | var FLOAT32 = RegisterType("float32", float32(0.0), []float32{})
113 | var FLOAT64 = RegisterType("float64", float64(0.0), []float64{})
114 | var COMPLEX64 = RegisterType("complex64", complex64(0), []complex64{})
115 | var COMPLEX128 = RegisterType("complex128", complex128(0), []complex128{})
116 |
--------------------------------------------------------------------------------
/raw/type_test.go:
--------------------------------------------------------------------------------
1 | // Originally cloned from `github.com/tones111/raw`
2 | //
3 | // Copyright (c) 2011 Eleanor McHugh
4 | //
5 | // For addtional deatils, see the included `LICENSE` file
6 |
7 | package raw
8 |
9 | import "testing"
10 |
11 | func TestConcreteValue(t *testing.T) { t.Log("Test not yet implemented") }
12 | func TestMakeAddressable(t *testing.T) { t.Log("Test not yet implemented") }
13 | func TestAssign(t *testing.T) { t.Log("Test not yet implemented") }
14 |
15 | func TestCompatible(t *testing.T) {
16 | ConfirmCompatible := func(l, r interface{}) {
17 | switch {
18 | case !Compatible(l, r):
19 | t.Fatalf("Compatible(%v, %v) should be true but is false", l, r)
20 | case !Compatible(r, l):
21 | t.Fatalf("Compatible(%v, %v) should be true but is false", l, r)
22 | }
23 | }
24 |
25 | RefuteCompatible := func(l, r interface{}) {
26 | switch {
27 | case Compatible(l, r):
28 | t.Fatalf("Compatible(%v, %v) should be false but is true", l, r)
29 | case Compatible(r, l):
30 | t.Fatalf("Compatible(%v, %v) should be false but is true", l, r)
31 | }
32 | }
33 |
34 | ConfirmCompatible([]int{}, []int{})
35 | ConfirmCompatible([0]int{}, [0]int{})
36 | ConfirmCompatible([0]int{}, [1]int{})
37 | ConfirmCompatible([]int{0}, [1]int{})
38 |
39 | RefuteCompatible([]int{}, []uint{})
40 | RefuteCompatible([0]int{}, [0]uint{})
41 | RefuteCompatible([0]int{}, [1]uint{})
42 | RefuteCompatible([]int{0}, [1]uint{})
43 |
44 | ConfirmCompatible([]int{}, map[int]int{})
45 | ConfirmCompatible([0]int{}, map[int]int{})
46 | ConfirmCompatible([1]int{}, map[int]int{})
47 | ConfirmCompatible([]int{0}, map[int]int{})
48 | }
49 |
--------------------------------------------------------------------------------