Add stubs for Direct3D9 backend.
[cairo/gpu.git] / src / cairo-misc.c
blob96815e504c008e02a8ce4c43b24bf65570b418e6
1 /* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */
2 /* cairo - a vector graphics library with display and print output
4 * Copyright © 2002 University of Southern California
5 * Copyright © 2005 Red Hat, Inc.
6 * Copyright © 2007 Adrian Johnson
8 * This library is free software; you can redistribute it and/or
9 * modify it either under the terms of the GNU Lesser General Public
10 * License version 2.1 as published by the Free Software Foundation
11 * (the "LGPL") or, at your option, under the terms of the Mozilla
12 * Public License Version 1.1 (the "MPL"). If you do not alter this
13 * notice, a recipient may use your version of this file under either
14 * the MPL or the LGPL.
16 * You should have received a copy of the LGPL along with this library
17 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 * You should have received a copy of the MPL along with this library
20 * in the file COPYING-MPL-1.1
22 * The contents of this file are subject to the Mozilla Public License
23 * Version 1.1 (the "License"); you may not use this file except in
24 * compliance with the License. You may obtain a copy of the License at
25 * http://www.mozilla.org/MPL/
27 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
28 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
29 * the specific language governing rights and limitations.
31 * The Original Code is the cairo graphics library.
33 * The Initial Developer of the Original Code is University of Southern
34 * California.
36 * Contributor(s):
37 * Carl D. Worth <cworth@cworth.org>
38 * Adrian Johnson <ajohnson@redneon.com>
41 #include "cairoint.h"
43 COMPILE_TIME_ASSERT (CAIRO_STATUS_LAST_STATUS < CAIRO_INT_STATUS_UNSUPPORTED);
44 COMPILE_TIME_ASSERT (CAIRO_INT_STATUS_LAST_STATUS <= 127);
46 /* Public stuff */
48 /**
49 * cairo_status_to_string:
50 * @status: a cairo status
52 * Provides a human-readable description of a #cairo_status_t.
54 * Returns: a string representation of the status
56 const char *
57 cairo_status_to_string (cairo_status_t status)
59 switch (status) {
60 case CAIRO_STATUS_SUCCESS:
61 return "no error has occurred";
62 case CAIRO_STATUS_NO_MEMORY:
63 return "out of memory";
64 case CAIRO_STATUS_INVALID_RESTORE:
65 return "cairo_restore() without matching cairo_save()";
66 case CAIRO_STATUS_INVALID_POP_GROUP:
67 return "no saved group to pop, i.e. cairo_pop_group() without matching cairo_push_group()";
68 case CAIRO_STATUS_NO_CURRENT_POINT:
69 return "no current point defined";
70 case CAIRO_STATUS_INVALID_MATRIX:
71 return "invalid matrix (not invertible)";
72 case CAIRO_STATUS_INVALID_STATUS:
73 return "invalid value for an input cairo_status_t";
74 case CAIRO_STATUS_NULL_POINTER:
75 return "NULL pointer";
76 case CAIRO_STATUS_INVALID_STRING:
77 return "input string not valid UTF-8";
78 case CAIRO_STATUS_INVALID_PATH_DATA:
79 return "input path data not valid";
80 case CAIRO_STATUS_READ_ERROR:
81 return "error while reading from input stream";
82 case CAIRO_STATUS_WRITE_ERROR:
83 return "error while writing to output stream";
84 case CAIRO_STATUS_SURFACE_FINISHED:
85 return "the target surface has been finished";
86 case CAIRO_STATUS_SURFACE_TYPE_MISMATCH:
87 return "the surface type is not appropriate for the operation";
88 case CAIRO_STATUS_PATTERN_TYPE_MISMATCH:
89 return "the pattern type is not appropriate for the operation";
90 case CAIRO_STATUS_INVALID_CONTENT:
91 return "invalid value for an input cairo_content_t";
92 case CAIRO_STATUS_INVALID_FORMAT:
93 return "invalid value for an input cairo_format_t";
94 case CAIRO_STATUS_INVALID_VISUAL:
95 return "invalid value for an input Visual*";
96 case CAIRO_STATUS_FILE_NOT_FOUND:
97 return "file not found";
98 case CAIRO_STATUS_INVALID_DASH:
99 return "invalid value for a dash setting";
100 case CAIRO_STATUS_INVALID_DSC_COMMENT:
101 return "invalid value for a DSC comment";
102 case CAIRO_STATUS_INVALID_INDEX:
103 return "invalid index passed to getter";
104 case CAIRO_STATUS_CLIP_NOT_REPRESENTABLE:
105 return "clip region not representable in desired format";
106 case CAIRO_STATUS_TEMP_FILE_ERROR:
107 return "error creating or writing to a temporary file";
108 case CAIRO_STATUS_INVALID_STRIDE:
109 return "invalid value for stride";
110 case CAIRO_STATUS_FONT_TYPE_MISMATCH:
111 return "the font type is not appropriate for the operation";
112 case CAIRO_STATUS_USER_FONT_IMMUTABLE:
113 return "the user-font is immutable";
114 case CAIRO_STATUS_USER_FONT_ERROR:
115 return "error occurred in a user-font callback function";
116 case CAIRO_STATUS_NEGATIVE_COUNT:
117 return "negative number used where it is not allowed";
118 case CAIRO_STATUS_INVALID_CLUSTERS:
119 return "input clusters do not represent the accompanying text and glyph arrays";
120 case CAIRO_STATUS_INVALID_SLANT:
121 return "invalid value for an input cairo_font_slant_t";
122 case CAIRO_STATUS_INVALID_WEIGHT:
123 return "invalid value for an input cairo_font_weight_t";
124 case CAIRO_STATUS_INVALID_SIZE:
125 return "invalid value (typically too big) for the size of the input (surface, pattern, etc.)";
126 case CAIRO_STATUS_USER_FONT_NOT_IMPLEMENTED:
127 return "user-font method not implemented";
128 default:
129 case CAIRO_STATUS_LAST_STATUS:
130 return "<unknown error status>";
136 * cairo_glyph_allocate:
137 * @num_glyphs: number of glyphs to allocate
139 * Allocates an array of #cairo_glyph_t's.
140 * This function is only useful in implementations of
141 * #cairo_user_scaled_font_text_to_glyphs_func_t where the user
142 * needs to allocate an array of glyphs that cairo will free.
143 * For all other uses, user can use their own allocation method
144 * for glyphs.
146 * This function returns %NULL if @num_glyphs is not positive,
147 * or if out of memory. That means, the %NULL return value
148 * signals out-of-memory only if @num_glyphs was positive.
150 * Returns: the newly allocated array of glyphs that should be
151 * freed using cairo_glyph_free()
153 * Since: 1.8
155 cairo_glyph_t *
156 cairo_glyph_allocate (int num_glyphs)
158 if (num_glyphs <= 0)
159 return NULL;
161 return _cairo_malloc_ab (num_glyphs, sizeof (cairo_glyph_t));
163 slim_hidden_def (cairo_glyph_allocate);
166 * cairo_glyph_free:
167 * @glyphs: array of glyphs to free, or %NULL
169 * Frees an array of #cairo_glyph_t's allocated using cairo_glyph_allocate().
170 * This function is only useful to free glyph array returned
171 * by cairo_scaled_font_text_to_glyphs() where cairo returns
172 * an array of glyphs that the user will free.
173 * For all other uses, user can use their own allocation method
174 * for glyphs.
176 * Since: 1.8
178 void
179 cairo_glyph_free (cairo_glyph_t *glyphs)
181 if (glyphs)
182 free (glyphs);
184 slim_hidden_def (cairo_glyph_free);
187 * cairo_text_cluster_allocate:
188 * @num_clusters: number of text_clusters to allocate
190 * Allocates an array of #cairo_text_cluster_t's.
191 * This function is only useful in implementations of
192 * #cairo_user_scaled_font_text_to_glyphs_func_t where the user
193 * needs to allocate an array of text clusters that cairo will free.
194 * For all other uses, user can use their own allocation method
195 * for text clusters.
197 * This function returns %NULL if @num_clusters is not positive,
198 * or if out of memory. That means, the %NULL return value
199 * signals out-of-memory only if @num_clusters was positive.
201 * Returns: the newly allocated array of text clusters that should be
202 * freed using cairo_text_cluster_free()
204 * Since: 1.8
206 cairo_text_cluster_t *
207 cairo_text_cluster_allocate (int num_clusters)
209 if (num_clusters <= 0)
210 return NULL;
212 return _cairo_malloc_ab (num_clusters, sizeof (cairo_text_cluster_t));
214 slim_hidden_def (cairo_text_cluster_allocate);
217 * cairo_text_cluster_free:
218 * @clusters: array of text clusters to free, or %NULL
220 * Frees an array of #cairo_text_cluster's allocated using cairo_text_cluster_allocate().
221 * This function is only useful to free text cluster array returned
222 * by cairo_scaled_font_text_to_glyphs() where cairo returns
223 * an array of text clusters that the user will free.
224 * For all other uses, user can use their own allocation method
225 * for text clusters.
227 * Since: 1.8
229 void
230 cairo_text_cluster_free (cairo_text_cluster_t *clusters)
232 if (clusters)
233 free (clusters);
235 slim_hidden_def (cairo_text_cluster_free);
238 /* Private stuff */
241 * _cairo_validate_text_clusters:
242 * @utf8: UTF-8 text
243 * @utf8_len: length of @utf8 in bytes
244 * @glyphs: array of glyphs
245 * @num_glyphs: number of glyphs
246 * @clusters: array of cluster mapping information
247 * @num_clusters: number of clusters in the mapping
248 * @cluster_flags: cluster flags
250 * Check that clusters cover the entire glyphs and utf8 arrays,
251 * and that cluster boundaries are UTF-8 boundaries.
253 * Return value: %CAIRO_STATUS_SUCCESS upon success, or
254 * %CAIRO_STATUS_INVALID_CLUSTERS on error.
255 * The error is either invalid UTF-8 input,
256 * or bad cluster mapping.
258 cairo_status_t
259 _cairo_validate_text_clusters (const char *utf8,
260 int utf8_len,
261 const cairo_glyph_t *glyphs,
262 int num_glyphs,
263 const cairo_text_cluster_t *clusters,
264 int num_clusters,
265 cairo_text_cluster_flags_t cluster_flags)
267 cairo_status_t status;
268 unsigned int n_bytes = 0;
269 unsigned int n_glyphs = 0;
270 int i;
272 for (i = 0; i < num_clusters; i++) {
273 int cluster_bytes = clusters[i].num_bytes;
274 int cluster_glyphs = clusters[i].num_glyphs;
276 if (cluster_bytes < 0 || cluster_glyphs < 0)
277 goto BAD;
279 /* A cluster should cover at least one character or glyph.
280 * I can't see any use for a 0,0 cluster.
281 * I can't see an immediate use for a zero-text cluster
282 * right now either, but they don't harm.
283 * Zero-glyph clusters on the other hand are useful for
284 * things like U+200C ZERO WIDTH NON-JOINER */
285 if (cluster_bytes == 0 && cluster_glyphs == 0)
286 goto BAD;
288 /* Since n_bytes and n_glyphs are unsigned, but the rest of
289 * values involved are signed, we can detect overflow easily */
290 if (n_bytes+cluster_bytes > (unsigned int)utf8_len || n_glyphs+cluster_glyphs > (unsigned int)num_glyphs)
291 goto BAD;
293 /* Make sure we've got valid UTF-8 for the cluster */
294 status = _cairo_utf8_to_ucs4 (utf8+n_bytes, cluster_bytes, NULL, NULL);
295 if (unlikely (status))
296 return _cairo_error (CAIRO_STATUS_INVALID_CLUSTERS);
298 n_bytes += cluster_bytes ;
299 n_glyphs += cluster_glyphs;
302 if (n_bytes != (unsigned int) utf8_len || n_glyphs != (unsigned int) num_glyphs) {
303 BAD:
304 return _cairo_error (CAIRO_STATUS_INVALID_CLUSTERS);
307 return CAIRO_STATUS_SUCCESS;
311 * _cairo_operator_bounded_by_mask:
312 * @op: a #cairo_operator_t
314 * A bounded operator is one where mask pixel
315 * of zero results in no effect on the destination image.
317 * Unbounded operators often require special handling; if you, for
318 * example, draw trapezoids with an unbounded operator, the effect
319 * extends past the bounding box of the trapezoids.
321 * Return value: %TRUE if the operator is bounded by the mask operand
323 cairo_bool_t
324 _cairo_operator_bounded_by_mask (cairo_operator_t op)
326 switch (op) {
327 case CAIRO_OPERATOR_CLEAR:
328 case CAIRO_OPERATOR_SOURCE:
329 case CAIRO_OPERATOR_OVER:
330 case CAIRO_OPERATOR_ATOP:
331 case CAIRO_OPERATOR_DEST:
332 case CAIRO_OPERATOR_DEST_OVER:
333 case CAIRO_OPERATOR_DEST_OUT:
334 case CAIRO_OPERATOR_XOR:
335 case CAIRO_OPERATOR_ADD:
336 case CAIRO_OPERATOR_SATURATE:
337 return TRUE;
338 case CAIRO_OPERATOR_OUT:
339 case CAIRO_OPERATOR_IN:
340 case CAIRO_OPERATOR_DEST_IN:
341 case CAIRO_OPERATOR_DEST_ATOP:
342 return FALSE;
345 ASSERT_NOT_REACHED;
346 return FALSE;
350 * _cairo_operator_bounded_by_source:
351 * @op: a #cairo_operator_t
353 * A bounded operator is one where source pixels of zero
354 * (in all four components, r, g, b and a) effect no change
355 * in the resulting destination image.
357 * Unbounded operators often require special handling; if you, for
358 * example, copy a surface with the SOURCE operator, the effect
359 * extends past the bounding box of the source surface.
361 * Return value: %TRUE if the operator is bounded by the source operand
363 cairo_bool_t
364 _cairo_operator_bounded_by_source (cairo_operator_t op)
366 switch (op) {
367 case CAIRO_OPERATOR_OVER:
368 case CAIRO_OPERATOR_ATOP:
369 case CAIRO_OPERATOR_DEST:
370 case CAIRO_OPERATOR_DEST_OVER:
371 case CAIRO_OPERATOR_DEST_OUT:
372 case CAIRO_OPERATOR_XOR:
373 case CAIRO_OPERATOR_ADD:
374 case CAIRO_OPERATOR_SATURATE:
375 return TRUE;
376 case CAIRO_OPERATOR_CLEAR:
377 case CAIRO_OPERATOR_SOURCE:
378 case CAIRO_OPERATOR_OUT:
379 case CAIRO_OPERATOR_IN:
380 case CAIRO_OPERATOR_DEST_IN:
381 case CAIRO_OPERATOR_DEST_ATOP:
382 return FALSE;
385 ASSERT_NOT_REACHED;
386 return FALSE;
390 /* This function is identical to the C99 function lround(), except that it
391 * performs arithmetic rounding (floor(d + .5) instead of away-from-zero rounding) and
392 * has a valid input range of (INT_MIN, INT_MAX] instead of
393 * [INT_MIN, INT_MAX]. It is much faster on both x86 and FPU-less systems
394 * than other commonly used methods for rounding (lround, round, rint, lrint
395 * or float (d + 0.5)).
397 * The reason why this function is much faster on x86 than other
398 * methods is due to the fact that it avoids the fldcw instruction.
399 * This instruction incurs a large performance penalty on modern Intel
400 * processors due to how it prevents efficient instruction pipelining.
402 * The reason why this function is much faster on FPU-less systems is for
403 * an entirely different reason. All common rounding methods involve multiple
404 * floating-point operations. Each one of these operations has to be
405 * emulated in software, which adds up to be a large performance penalty.
406 * This function doesn't perform any floating-point calculations, and thus
407 * avoids this penalty.
410 _cairo_lround (double d)
412 uint32_t top, shift_amount, output;
413 union {
414 double d;
415 uint64_t ui64;
416 uint32_t ui32[2];
417 } u;
419 u.d = d;
421 /* If the integer word order doesn't match the float word order, we swap
422 * the words of the input double. This is needed because we will be
423 * treating the whole double as a 64-bit unsigned integer. Notice that we
424 * use WORDS_BIGENDIAN to detect the integer word order, which isn't
425 * exactly correct because WORDS_BIGENDIAN refers to byte order, not word
426 * order. Thus, we are making the assumption that the byte order is the
427 * same as the integer word order which, on the modern machines that we
428 * care about, is OK.
430 #if ( defined(FLOAT_WORDS_BIGENDIAN) && !defined(WORDS_BIGENDIAN)) || \
431 (!defined(FLOAT_WORDS_BIGENDIAN) && defined(WORDS_BIGENDIAN))
433 uint32_t temp = u.ui32[0];
434 u.ui32[0] = u.ui32[1];
435 u.ui32[1] = temp;
437 #endif
439 #ifdef WORDS_BIGENDIAN
440 #define MSW (0) /* Most Significant Word */
441 #define LSW (1) /* Least Significant Word */
442 #else
443 #define MSW (1)
444 #define LSW (0)
445 #endif
447 /* By shifting the most significant word of the input double to the
448 * right 20 places, we get the very "top" of the double where the exponent
449 * and sign bit lie.
451 top = u.ui32[MSW] >> 20;
453 /* Here, we calculate how much we have to shift the mantissa to normalize
454 * it to an integer value. We extract the exponent "top" by masking out the
455 * sign bit, then we calculate the shift amount by subtracting the exponent
456 * from the bias. Notice that the correct bias for 64-bit doubles is
457 * actually 1075, but we use 1053 instead for two reasons:
459 * 1) To perform rounding later on, we will first need the target
460 * value in a 31.1 fixed-point format. Thus, the bias needs to be one
461 * less: (1075 - 1: 1074).
463 * 2) To avoid shifting the mantissa as a full 64-bit integer (which is
464 * costly on certain architectures), we break the shift into two parts.
465 * First, the upper and lower parts of the mantissa are shifted
466 * individually by a constant amount that all valid inputs will require
467 * at the very least. This amount is chosen to be 21, because this will
468 * allow the two parts of the mantissa to later be combined into a
469 * single 32-bit representation, on which the remainder of the shift
470 * will be performed. Thus, we decrease the bias by an additional 21:
471 * (1074 - 21: 1053).
473 shift_amount = 1053 - (top & 0x7FF);
475 /* We are done with the exponent portion in "top", so here we shift it off
476 * the end.
478 top >>= 11;
480 /* Before we perform any operations on the mantissa, we need to OR in
481 * the implicit 1 at the top (see the IEEE-754 spec). We needn't mask
482 * off the sign bit nor the exponent bits because these higher bits won't
483 * make a bit of difference in the rest of our calculations.
485 u.ui32[MSW] |= 0x100000;
487 /* If the input double is negative, we have to decrease the mantissa
488 * by a hair. This is an important part of performing arithmetic rounding,
489 * as negative numbers must round towards positive infinity in the
490 * halfwase case of -x.5. Since "top" contains only the sign bit at this
491 * point, we can just decrease the mantissa by the value of "top".
493 u.ui64 -= top;
495 /* By decrementing "top", we create a bitmask with a value of either
496 * 0x0 (if the input was negative) or 0xFFFFFFFF (if the input was positive
497 * and thus the unsigned subtraction underflowed) that we'll use later.
499 top--;
501 /* Here, we shift the mantissa by the constant value as described above.
502 * We can emulate a 64-bit shift right by 21 through shifting the top 32
503 * bits left 11 places and ORing in the bottom 32 bits shifted 21 places
504 * to the right. Both parts of the mantissa are now packed into a single
505 * 32-bit integer. Although we severely truncate the lower part in the
506 * process, we still have enough significant bits to perform the conversion
507 * without error (for all valid inputs).
509 output = (u.ui32[MSW] << 11) | (u.ui32[LSW] >> 21);
511 /* Next, we perform the shift that converts the X.Y fixed-point number
512 * currently found in "output" to the desired 31.1 fixed-point format
513 * needed for the following rounding step. It is important to consider
514 * all possible values for "shift_amount" at this point:
516 * - {shift_amount < 0} Since shift_amount is an unsigned integer, it
517 * really can't have a value less than zero. But, if the shift_amount
518 * calculation above caused underflow (which would happen with
519 * input > INT_MAX or input <= INT_MIN) then shift_amount will now be
520 * a very large number, and so this shift will result in complete
521 * garbage. But that's OK, as the input was out of our range, so our
522 * output is undefined.
524 * - {shift_amount > 31} If the magnitude of the input was very small
525 * (i.e. |input| << 1.0), shift_amount will have a value greater than
526 * 31. Thus, this shift will also result in garbage. After performing
527 * the shift, we will zero-out "output" if this is the case.
529 * - {0 <= shift_amount < 32} In this case, the shift will properly convert
530 * the mantissa into a 31.1 fixed-point number.
532 output >>= shift_amount;
534 /* This is where we perform rounding with the 31.1 fixed-point number.
535 * Since what we're after is arithmetic rounding, we simply add the single
536 * fractional bit into the integer part of "output", and just keep the
537 * integer part.
539 output = (output >> 1) + (output & 1);
541 /* Here, we zero-out the result if the magnitude if the input was very small
542 * (as explained in the section above). Notice that all input out of the
543 * valid range is also caught by this condition, which means we produce 0
544 * for all invalid input, which is a nice side effect.
546 * The most straightforward way to do this would be:
548 * if (shift_amount > 31)
549 * output = 0;
551 * But we can use a little trick to avoid the potential branch. The
552 * expression (shift_amount > 31) will be either 1 or 0, which when
553 * decremented will be either 0x0 or 0xFFFFFFFF (unsigned underflow),
554 * which can be used to conditionally mask away all the bits in "output"
555 * (in the 0x0 case), effectively zeroing it out. Certain, compilers would
556 * have done this for us automatically.
558 output &= ((shift_amount > 31) - 1);
560 /* If the input double was a negative number, then we have to negate our
561 * output. The most straightforward way to do this would be:
563 * if (!top)
564 * output = -output;
566 * as "top" at this point is either 0x0 (if the input was negative) or
567 * 0xFFFFFFFF (if the input was positive). But, we can use a trick to
568 * avoid the branch. Observe that the following snippet of code has the
569 * same effect as the reference snippet above:
571 * if (!top)
572 * output = 0 - output;
573 * else
574 * output = output - 0;
576 * Armed with the bitmask found in "top", we can condense the two statements
577 * into the following:
579 * output = (output & top) - (output & ~top);
581 * where, in the case that the input double was negative, "top" will be 0,
582 * and the statement will be equivalent to:
584 * output = (0) - (output);
586 * and if the input double was positive, "top" will be 0xFFFFFFFF, and the
587 * statement will be equivalent to:
589 * output = (output) - (0);
591 * Which, as pointed out earlier, is equivalent to the original reference
592 * snippet.
594 output = (output & top) - (output & ~top);
596 return output;
597 #undef MSW
598 #undef LSW
602 #ifdef _WIN32
604 #define WIN32_LEAN_AND_MEAN
605 /* We require Windows 2000 features such as ETO_PDY */
606 #if !defined(WINVER) || (WINVER < 0x0500)
607 # define WINVER 0x0500
608 #endif
609 #if !defined(_WIN32_WINNT) || (_WIN32_WINNT < 0x0500)
610 # define _WIN32_WINNT 0x0500
611 #endif
613 #include <windows.h>
614 #include <io.h>
616 #if !_WIN32_WCE
617 /* tmpfile() replacement for Windows.
619 * On Windows tmpfile() creates the file in the root directory. This
620 * may fail due to unsufficient privileges. However, this isn't a
621 * problem on Windows CE so we don't use it there.
623 FILE *
624 _cairo_win32_tmpfile (void)
626 DWORD path_len;
627 WCHAR path_name[MAX_PATH + 1];
628 WCHAR file_name[MAX_PATH + 1];
629 HANDLE handle;
630 int fd;
631 FILE *fp;
633 path_len = GetTempPathW (MAX_PATH, path_name);
634 if (path_len <= 0 || path_len >= MAX_PATH)
635 return NULL;
637 if (GetTempFileNameW (path_name, L"ps_", 0, file_name) == 0)
638 return NULL;
640 handle = CreateFileW (file_name,
641 GENERIC_READ | GENERIC_WRITE,
643 NULL,
644 CREATE_ALWAYS,
645 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE,
646 NULL);
647 if (handle == INVALID_HANDLE_VALUE) {
648 DeleteFileW (file_name);
649 return NULL;
652 fd = _open_osfhandle((intptr_t) handle, 0);
653 if (fd < 0) {
654 CloseHandle (handle);
655 return NULL;
658 fp = fdopen(fd, "w+b");
659 if (fp == NULL) {
660 _close(fd);
661 return NULL;
664 return fp;
666 #endif /* !_WIN32_WCE */
668 #endif /* _WIN32 */
670 typedef struct _cairo_intern_string {
671 cairo_hash_entry_t hash_entry;
672 int len;
673 char *string;
674 } cairo_intern_string_t;
676 static cairo_hash_table_t *_cairo_intern_string_ht;
678 static unsigned long
679 _intern_string_hash (const char *str, int len)
681 const signed char *p = (const signed char *) str;
682 unsigned int h = *p;
684 for (p += 1; --len; p++)
685 h = (h << 5) - h + *p;
687 return h;
690 static cairo_bool_t
691 _intern_string_equal (const void *_a, const void *_b)
693 const cairo_intern_string_t *a = _a;
694 const cairo_intern_string_t *b = _b;
696 if (a->len != b->len)
697 return FALSE;
699 return memcmp (a->string, b->string, a->len) == 0;
702 cairo_status_t
703 _cairo_intern_string (const char **str_inout, int len)
705 char *str = (char *) *str_inout;
706 cairo_intern_string_t tmpl, *istring;
707 cairo_status_t status = CAIRO_STATUS_SUCCESS;
709 if (CAIRO_INJECT_FAULT ())
710 return _cairo_error (CAIRO_STATUS_NO_MEMORY);
712 if (len < 0)
713 len = strlen (str);
714 tmpl.hash_entry.hash = _intern_string_hash (str, len);
715 tmpl.len = len;
716 tmpl.string = (char *) str;
718 CAIRO_MUTEX_LOCK (_cairo_intern_string_mutex);
719 if (_cairo_intern_string_ht == NULL) {
720 _cairo_intern_string_ht = _cairo_hash_table_create (_intern_string_equal);
721 if (unlikely (_cairo_intern_string_ht == NULL)) {
722 status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
723 goto BAIL;
727 istring = _cairo_hash_table_lookup (_cairo_intern_string_ht,
728 &tmpl.hash_entry);
729 if (istring == NULL) {
730 istring = malloc (sizeof (cairo_intern_string_t) + len + 1);
731 if (likely (istring != NULL)) {
732 istring->hash_entry.hash = tmpl.hash_entry.hash;
733 istring->len = tmpl.len;
734 istring->string = (char *) (istring + 1);
735 memcpy (istring->string, str, len);
736 istring->string[len] = '\0';
738 status = _cairo_hash_table_insert (_cairo_intern_string_ht,
739 &istring->hash_entry);
740 if (unlikely (status)) {
741 free (istring);
742 goto BAIL;
744 } else {
745 status = _cairo_error (CAIRO_STATUS_NO_MEMORY);
746 goto BAIL;
750 *str_inout = istring->string;
752 BAIL:
753 CAIRO_MUTEX_UNLOCK (_cairo_intern_string_mutex);
754 return status;
757 static void
758 _intern_string_pluck (void *entry, void *closure)
760 _cairo_hash_table_remove (closure, entry);
761 free (entry);
764 void
765 _cairo_intern_string_reset_static_data (void)
767 CAIRO_MUTEX_LOCK (_cairo_intern_string_mutex);
768 if (_cairo_intern_string_ht != NULL) {
769 _cairo_hash_table_foreach (_cairo_intern_string_ht,
770 _intern_string_pluck,
771 _cairo_intern_string_ht);
772 _cairo_hash_table_destroy(_cairo_intern_string_ht);
773 _cairo_intern_string_ht = NULL;
775 CAIRO_MUTEX_UNLOCK (_cairo_intern_string_mutex);
778 long long _cairo_last_id = 0;
781 extern long long _cairo_last_id;
782 extern cairo_mutex_t _cairo_last_id_mutex;
784 long long _cairo_id(void)
786 /* i586, x86-64 */
787 #ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8
788 return __sync_add_and_fetch(&_cairo_last_id, 1LL);
789 #else
790 #if defined(__i386__) && !defined(__i586__)
791 #warning Compile Cairo for 586 or later for better performance
792 #endif
793 long long id;
794 CAIRO_MUTEX_LOCK(_cairo_last_id_mutex);
795 id = ++_cairo_last_id;
796 CAIRO_MUTEX_UNLOCK(_cairo_last_id_mutex);
797 return id;
798 #endif