1#include "pyobjc.h"
2
3#if PY_MAJOR_VERSION == 2
4
5PyObject* 
6PyObjCString_InternFromStringAndSize(const char* v, Py_ssize_t l)
7{
8	PyObject* result;
9
10	result = PyString_FromStringAndSize(v, l);
11	if (result == NULL) {
12		return NULL;
13	}
14	PyString_InternInPlace(&result);
15	return result;
16}
17
18
19
20#ifndef PY_FORMAT_LONG_LONG 
21#define   PY_FORMAT_LONG_LONG "ll"
22#endif
23
24/* 
25 * This function is PyString_FromFormat from Python 2.7 + support for
26 * '%R' and '%S'.
27 */
28static PyObject* 
29PyObjCString_FromFormatV(const char* format, va_list vargs)
30{
31	va_list count;
32	Py_ssize_t n = 0;
33	const char* f;
34	char *s;
35	PyObject* string;
36        Py_ssize_t callcount = 0;
37	PyObject **callresults = NULL;
38        PyObject **callresult = NULL;
39
40#ifdef VA_LIST_IS_ARRAY
41	Py_MEMCPY(count, vargs, sizeof(va_list));
42#else
43#ifdef  __va_copy
44	__va_copy(count, vargs);
45#else
46	count = vargs;
47#endif
48#endif
49	 /* step 0: count the number of %S/%R format specifications
50	  * (we call PyObject_Str()/PyObject_Repr() for these
51	  * objects once during step 1 and put the result in an array) 
52	  */
53	for (f = format; *f; f++) {
54		if (*f == '%') {
55			if (*(f+1)=='%')
56				continue;
57			if (*(f+1)=='S' || *(f+1)=='R')
58				++callcount;
59		 }
60	}
61	if (callcount) {
62		callresults = PyObject_Malloc(sizeof(PyObject *)*callcount);
63		if (!callresults) {
64			PyErr_NoMemory();
65			return NULL;
66		}
67		callresult = callresults;
68	}
69
70	/* step 1: figure out how large a buffer we need */
71	for (f = format; *f; f++) {
72		if (*f == '%') {
73#ifdef HAVE_LONG_LONG
74			int longlongflag = 0;
75#endif
76			const char* p = f;
77			while (*++f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
78				;
79
80			/* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
81			 * they don't affect the amount of space we reserve.
82			 */
83			if (*f == 'l') {
84				if (f[1] == 'd' || f[1] == 'u') {
85					++f;
86				}
87#ifdef HAVE_LONG_LONG
88				else if (f[1] == 'l' &&
89					 (f[2] == 'd' || f[2] == 'u')) {
90					longlongflag = 1;
91					f += 2;
92				}
93#endif
94			}
95			else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
96				++f;
97			}
98
99			switch (*f) {
100			case 'c':
101				(void)va_arg(count, int);
102				/* fall through... */
103			case '%':
104				n++;
105				break;
106			case 'd': case 'u': case 'i': case 'x':
107				(void) va_arg(count, int);
108#ifdef HAVE_LONG_LONG
109				/* Need at most
110				   ceil(log10(256)*SIZEOF_LONG_LONG) digits,
111				   plus 1 for the sign.  53/22 is an upper
112				   bound for log10(256). */
113				if (longlongflag)
114					n += 2 + (SIZEOF_LONG_LONG*53-1) / 22;
115				else
116#endif
117					/* 20 bytes is enough to hold a 64-bit
118					   integer.  Decimal takes the most
119					   space.  This isn't enough for
120					   octal. */
121					n += 20;
122
123				break;
124			case 's':
125				s = va_arg(count, char*);
126				n += strlen(s);
127				break;
128			case 'p':
129				(void) va_arg(count, int);
130				/* maximum 64-bit pointer representation:
131				 * 0xffffffffffffffff
132				 * so 19 characters is enough.
133				 * XXX I count 18 -- what's the extra for?
134				 */
135				n += 19;
136				break;
137
138			case 'R':
139			{
140				PyObject *obj = va_arg(count, PyObject *);
141				PyObject *str;
142				assert(obj);
143				str = PyObject_Repr(obj);
144				if (!str)
145				    goto fail;
146				if (!PyString_Check(str)) {
147					PyErr_SetString(PyExc_TypeError,
148						"repr() returned non-string");
149					goto fail;
150				}
151				n += PyString_GET_SIZE(str);
152				/* Remember the str and switch to the next slot */
153				*callresult++ = str;
154			}
155			break;
156
157			case 'S':
158			{
159				PyObject *obj = va_arg(count, PyObject *);
160				PyObject *str;
161				assert(obj);
162				str = PyObject_Str(obj);
163				if (!str)
164				    goto fail;
165				if (!PyString_Check(str)) {
166					PyErr_SetString(PyExc_TypeError,
167						"str() returned non-string");
168					goto fail;
169				}
170				n += PyString_GET_SIZE(str);
171				/* Remember the str and switch to the next slot */
172				*callresult++ = str;
173			}
174			break;
175
176			default:
177				/* if we stumble upon an unknown
178				   formatting code, copy the rest of
179				   the format string to the output
180				   string. (we cannot just skip the
181				   code, since there's no way to know
182				   what's in the argument list) */
183				n += strlen(p);
184				goto expand;
185			}
186		} else
187			n++;
188	}
189 expand:
190	/* step 2: fill the buffer */
191	/* Since we've analyzed how much space we need for the worst case,
192	   use sprintf directly instead of the slower PyOS_snprintf. */
193	string = PyString_FromStringAndSize(NULL, n);
194	if (!string)
195		return NULL;
196
197	s = PyString_AsString(string);
198
199	callresult = callresults;
200	for (f = format; *f; f++) {
201		if (*f == '%') {
202			const char* p = f++;
203			Py_ssize_t i;
204			int longflag = 0;
205#ifdef HAVE_LONG_LONG
206			int longlongflag = 0;
207#endif
208			int size_tflag = 0;
209			/* parse the width.precision part (we're only
210			   interested in the precision value, if any) */
211			n = 0;
212			while (isdigit(Py_CHARMASK(*f)))
213				n = (n*10) + *f++ - '0';
214			if (*f == '.') {
215				f++;
216				n = 0;
217				while (isdigit(Py_CHARMASK(*f)))
218					n = (n*10) + *f++ - '0';
219			}
220			while (*f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
221				f++;
222			/* Handle %ld, %lu, %lld and %llu. */
223			if (*f == 'l') {
224				if (f[1] == 'd' || f[1] == 'u') {
225					longflag = 1;
226					++f;
227				}
228#ifdef HAVE_LONG_LONG
229				else if (f[1] == 'l' &&
230					 (f[2] == 'd' || f[2] == 'u')) {
231					longlongflag = 1;
232					f += 2;
233				}
234#endif
235			}
236			/* handle the size_t flag. */
237			else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
238				size_tflag = 1;
239				++f;
240			}
241
242			switch (*f) {
243			case 'c':
244				*s++ = va_arg(vargs, int);
245				break;
246			case 'd':
247				if (longflag)
248					sprintf(s, "%ld", va_arg(vargs, long));
249#ifdef HAVE_LONG_LONG
250				else if (longlongflag)
251					sprintf(s, "%" PY_FORMAT_LONG_LONG "d",
252						va_arg(vargs, PY_LONG_LONG));
253#endif
254				else if (size_tflag)
255					sprintf(s, "%" PY_FORMAT_SIZE_T "d",
256					        va_arg(vargs, Py_ssize_t));
257				else
258					sprintf(s, "%d", va_arg(vargs, int));
259				s += strlen(s);
260				break;
261			case 'u':
262				if (longflag)
263					sprintf(s, "%lu",
264						va_arg(vargs, unsigned long));
265#ifdef HAVE_LONG_LONG
266				else if (longlongflag)
267					sprintf(s, "%" PY_FORMAT_LONG_LONG "u",
268						va_arg(vargs, PY_LONG_LONG));
269#endif
270				else if (size_tflag)
271					sprintf(s, "%" PY_FORMAT_SIZE_T "u",
272					        va_arg(vargs, size_t));
273				else
274					sprintf(s, "%u",
275						va_arg(vargs, unsigned int));
276				s += strlen(s);
277				break;
278			case 'i':
279				sprintf(s, "%i", va_arg(vargs, int));
280				s += strlen(s);
281				break;
282			case 'x':
283				sprintf(s, "%x", va_arg(vargs, int));
284				s += strlen(s);
285				break;
286			case 's':
287				p = va_arg(vargs, char*);
288				i = strlen(p);
289				if (n > 0 && i > n)
290					i = n;
291				Py_MEMCPY(s, p, i);
292				s += i;
293				break;
294			case 'p':
295				sprintf(s, "%p", va_arg(vargs, void*));
296				/* %p is ill-defined:  ensure leading 0x. */
297				if (s[1] == 'X')
298					s[1] = 'x';
299				else if (s[1] != 'x') {
300					memmove(s+2, s, strlen(s)+1);
301					s[0] = '0';
302					s[1] = 'x';
303				}
304				s += strlen(s);
305				break;
306
307			case 'R':
308			case 'S':
309			   {
310				/* unused, since we already have the result */
311				(void) va_arg(vargs, PyObject *);
312
313				/* FIXME: The clang analyzer thinks that 'callresult' might be 
314				 * NULL here. That's wrong, this is the second loop through 
315				 * the format string and on the previous loop callresults got
316				 * created and filled.
317				 */
318
319				if (callresult != NULL) {
320					memcpy(s, PyString_AS_STRING(*callresult),
321					  PyString_GET_SIZE(*callresult));
322					s += PyString_GET_SIZE(*callresult);
323					Py_DECREF(*callresult); *callresult = NULL;
324				}
325				callresult++;
326				break;
327			    }
328
329			case '%':
330				*s++ = '%';
331				break;
332			default:
333				strcpy(s, p);
334				s += strlen(s);
335				goto end;
336			}
337		} else
338			*s++ = *f;
339	}
340
341 end:
342	if (callresults) {
343		PyObject_Free(callresults);
344        }
345	_PyString_Resize(&string, s - PyString_AS_STRING(string));
346	return string;
347
348 fail:
349	if (callresults) {
350		PyObject **callresult2 = callresults;
351		while (callresult2 < callresult) {
352		    Py_DECREF(*callresult2);
353		    ++callresult2;
354		}
355		PyObject_Free(callresults);
356        }
357	return NULL;
358}
359
360PyObject* PyObjCErr_Format(PyObject* exception, const char* format, ...)
361{
362	/* This is an enhanced version of PyErr_Format for python 2.x that
363	 * accept much of the format characters that are supported in python 3
364	 */
365	PyObject* strval;
366	va_list args;
367	va_start(args, format);
368	strval = PyObjCString_FromFormatV(format, args);
369	va_end(args);
370	if (strval) {
371		PyErr_SetObject(exception, strval);
372		Py_DECREF(strval);
373	}
374	return NULL;
375}
376
377#else /* Py3k */
378
379int PyObject_Cmp (PyObject *o1, PyObject *o2, int *result)
380{
381	int r;
382	
383	r = PyObject_RichCompareBool(o1, o2, Py_EQ);
384	if (r == -1) {
385		return -1;
386	} else if (r == 1) {
387		*result = 0;
388		return 0;
389	}
390
391	r = PyObject_RichCompareBool(o1, o2, Py_LT);
392	if (r == -1) {
393		return -1;
394	} else if (r == 1) {
395		*result = -1;
396		return 0;
397	} 
398
399	r = PyObject_RichCompareBool(o1, o2, Py_GT);
400	if (r == -1) {
401		return 1;
402	} else if (r == 1) {
403		*result = 1;
404		return 0;
405	} 
406
407	PyErr_Format(PyExc_TypeError, "%R and %R cannot be compared",
408			o1, o2);
409	return -1;
410}
411
412static PyObject* registry = NULL;
413
414PyObject* PyBytes_InternFromString(const char* v)
415{
416	PyObject* key;
417	PyObject* value;
418
419	if (registry == NULL) {
420		registry = PyDict_New();
421		if (registry == NULL) {
422			return NULL;
423		}
424	}
425
426	key = PyBytes_FromString(v);
427	if (key == NULL) {
428		return NULL;
429	}
430	value = PyDict_GetItem(registry, key);
431	if (value == NULL) {
432		int r = PyDict_SetItem(registry, key, key);
433		if (r == -1) {
434			Py_DECREF(key);
435			return NULL;
436		} else {
437			return key;
438		}
439	} else {
440		Py_DECREF(key);
441		Py_INCREF(value);
442		return value;
443	}
444}
445
446PyObject* PyBytes_InternFromStringAndSize(const char* v, Py_ssize_t l)
447{
448	PyObject* key;
449	PyObject* value;
450
451	if (registry == NULL) {
452		registry = PyDict_New();
453		if (registry == NULL) {
454			return NULL;
455		}
456	}
457
458	key = PyBytes_FromStringAndSize(v, l);
459	if (key == NULL) {
460		return NULL;
461	}
462	value = PyDict_GetItem(registry, key);
463	if (value == NULL) {
464		int r = PyDict_SetItem(registry, key, key);
465		if (r == -1) {
466			Py_DECREF(key);
467			return NULL;
468		} else {
469			return key;
470		}
471	} else {
472		Py_DECREF(key);
473		Py_INCREF(value);
474		return value;
475	}
476}
477
478
479#endif /* Py3K */
480
481/* 
482 * Helper function for making sure that we don't store duplicate data
483 * for the metadata bridges.
484 *
485 * Interface: call on value, don't update value afterwards. Steals
486 * reference to argument and returns a new reference.
487 */
488static	PyObject* intern_mapping = NULL;
489
490void	  PyObjC_ClearIntern(void)
491{
492	Py_CLEAR(intern_mapping);
493}
494
495PyObject* PyObjC_InternValue(PyObject* orig)
496{
497	return orig;
498}
499
500PyObject* PyObjC_IntFromString(char* v, char**pend, int base)
501{
502	PyObject* r = PyInt_FromString(v, pend, base);
503	if (r == NULL) {
504		return NULL;
505	}
506	return PyObjC_InternValue(r);
507}
508
509
510PyObject* PyObjC_IntFromLong(long v)
511{
512	PyObject* r = PyInt_FromLong(v);
513	if (r == NULL) {
514		return NULL;
515	}
516	return PyObjC_InternValue(r);
517}
518