cython

Форк
0
/
cpp_stl_string.pyx 
453 строки · 10.3 Кб
1
# mode: run
2
# tag: cpp, warnings
3

4
cimport cython
5

6
from libcpp.string cimport string, npos, to_string, stoi, stof
7

8
b_asdf = b'asdf'
9
b_asdg = b'asdg'
10
b_s = b's'
11

12

13
cdef int compare_to_asdf_ref(string& s) except -999:
14
    return s.compare(b"asdf")
15

16
def test_coerced_literal_ref():
17
    """
18
    >>> test_coerced_literal_ref()
19
    0
20
    """
21
    return compare_to_asdf_ref("asdf")
22

23

24
cdef int compare_to_asdf_const_ref(const string& s) except -999:
25
    return s.compare(b"asdf")
26

27
def test_coerced_literal_const_ref():
28
    """
29
    >>> test_coerced_literal_const_ref()
30
    0
31
    """
32
    return compare_to_asdf_const_ref("asdf")
33

34

35
cdef int compare_to_asdf_const(const string s) except -999:
36
    return s.compare(b"asdf")
37

38
def test_coerced_literal_const():
39
    """
40
    >>> test_coerced_literal_const()
41
    0
42
    """
43
    return compare_to_asdf_const("asdf")
44

45

46
def test_conversion(py_obj):
47
    """
48
    >>> test_conversion(b_asdf) == b_asdf or test_conversion(b_asdf)
49
    True
50
    >>> test_conversion(123)  # doctest: +ELLIPSIS
51
    Traceback (most recent call last):
52
    TypeError: expected ..., int found
53
    """
54
    cdef string s = py_obj
55
    return s
56

57
def test_indexing(char *py_str):
58
    """
59
    >>> test_indexing(b_asdf)
60
    ('s', 's')
61
    """
62
    cdef string s
63
    s = string(py_str)
64
    return chr(s[1]), chr(s.at(1))
65

66
def test_size(char *py_str):
67
    """
68
    >>> test_size(b_asdf)
69
    (4, 4)
70
    """
71
    cdef string s
72
    s = string(py_str)
73
    return s.size(), s.length()
74

75
def test_compare(char *a, char *b):
76
    """
77
    >>> test_compare(b_asdf, b_asdf)
78
    0
79

80
    >>> test_compare(b_asdf, b_asdg) < 0
81
    True
82
    """
83
    cdef string s = string(a)
84
    cdef string t = string(b)
85
    return s.compare(t)
86

87
def test_empty():
88
    """
89
    >>> test_empty()
90
    (True, False)
91
    """
92
    cdef string a = string(<char *>b"")
93
    cdef string b = string(<char *>b"aa")
94
    return a.empty(), b.empty()
95

96
def test_push_back(char *a):
97
    """
98
    >>> test_push_back(b_asdf) == b_asdf + b_s
99
    True
100
    """
101
    cdef string s = string(a)
102
    s.push_back(<char>ord('s'))
103
    return s.c_str()
104

105
def test_pop_back(char *a):
106
    """
107
    >>> test_pop_back(b'abc') == b'ab' or test_pop_back(b'abc')
108
    True
109
    """
110
    cdef string s = string(a)
111
    s.pop_back()
112
    return s
113

114
def test_insert(char *a, char *b, int i):
115
    """
116
    >>> test_insert('AAAA'.encode('ASCII'), 'BBBB'.encode('ASCII'), 2) == 'AABBBBAA'.encode('ASCII')
117
    True
118
    """
119
    cdef string s = string(a)
120
    cdef string t = string(b)
121
    cdef string u = s.insert(i, t)
122
    return u.c_str()
123

124
def test_copy(char *a):
125
    """
126
    >>> test_copy(b_asdf) == b_asdf[1:]
127
    True
128
    """
129
    cdef string t = string(a)
130
    cdef char[6] buffer
131
    cdef size_t length = t.copy(buffer, 4, 1)
132
    buffer[length] = c'\0'
133
    return buffer
134

135
def test_find(char *a, char *b):
136
    """
137
    >>> test_find(b_asdf, 'df'.encode('ASCII'))
138
    2
139
    """
140
    cdef string s = string(a)
141
    cdef string t = string(b)
142
    cdef size_t i = s.find(t)
143
    return i
144

145
def test_npos(char *a, char *b):
146
    """
147
    >>> test_npos(b'abc', b'x')
148
    True
149
    >>> test_npos(b'abc', b'a')
150
    False
151
    """
152
    cdef string s = string(a)
153
    cdef string st = string(b)
154
    return s.find(st) == npos
155

156
def test_clear():
157
    """
158
    >>> test_clear() == ''.encode('ASCII')
159
    True
160
    """
161
    cdef string s = string(<char *>"asdf")
162
    s.clear()
163
    return s.c_str()
164

165
def test_erase(char *a, size_t pos=0, size_t count=npos):
166
    """
167
    >>> test_erase(b'abc') == b'' or test_erase(b'abc')
168
    True
169
    >>> test_erase(b'abc', 1) == b'a' or test_erase(b'abc', 1)
170
    True
171
    >>> test_erase(b'abc', 1, 1) == b'ac' or test_erase(b'abc', 1, 1)
172
    True
173
    """
174
    cdef string s = string(a)
175
    return s.erase(pos, count)
176

177
def test_assign(char *a):
178
    """
179
    >>> test_assign(b_asdf) == 'ggg'.encode('ASCII')
180
    True
181
    """
182
    cdef string s = string(a)
183
    s.assign(<char *>"ggg")
184
    return s.c_str()
185

186

187
def test_substr(char *a):
188
    """
189
    >>> test_substr('ABCDEFGH'.encode('ASCII')) == ('BCDEFGH'.encode('ASCII'), 'BCDE'.encode('ASCII'), 'ABCDEFGH'.encode('ASCII'))
190
    True
191
    """
192
    cdef string s = string(a)
193
    cdef string x, y, z
194
    x = s.substr(1)
195
    y = s.substr(1, 4)
196
    z = s.substr()
197
    return x.c_str(), y.c_str(), z.c_str()
198

199
def test_replace(char *a, char *b, char* fill):
200
    """
201
    >>> test_replace(b_asdf, b_asdg, b_s)  == (b_asdg+b_asdf[2:], b_asdf[:-2]+b_asdg[-2:], (b_s*4)+b_asdg[2:])
202
    True
203
    """
204
    cdef string s1 = string(a)
205
    cdef string s2 = string(a)
206
    cdef string s3 = string(b)
207
    s1.replace(0, 2, s3)
208
    s2.replace(s2.size()-2, 2, s3, s3.size()-2, 2)
209
    s3.replace(0, 2, 4, fill[0])
210
    return s1.c_str(), s2.c_str(), s3.c_str()
211

212
def test_append(char *a, char *b):
213
    """
214
    >>> test_append(b_asdf, '1234'.encode('ASCII')) == b_asdf + '1234'.encode('ASCII')
215
    True
216
    """
217
    cdef string s = string(a)
218
    cdef string t = string(b)
219
    cdef string j = s.append(t)
220
    return j.c_str()
221

222
def test_char_compare(py_str):
223
    """
224
    >>> test_char_compare(b_asdf)
225
    True
226
    """
227
    cdef char *a = py_str
228
    cdef string b = string(a)
229
    return b.compare(b) == 0
230

231
def test_cstr(char *a):
232
    """
233
    >>> test_cstr(b_asdf) == b_asdf
234
    True
235
    """
236
    cdef string b = string(a)
237
    return b.c_str()
238

239
@cython.test_assert_path_exists("//PythonCapiCallNode")
240
@cython.test_fail_if_path_exists("//AttributeNode")
241
def test_decode(char* a):
242
    """
243
    >>> print(test_decode(b_asdf))
244
    asdf
245
    """
246
    cdef string b = string(a)
247
    return b.decode('ascii')
248

249

250
@cython.test_assert_path_exists("//ReturnStatNode//PythonCapiCallNode")
251
def test_cstr_decode(char* a):
252
    """
253
    >>> print(test_cstr_decode(b_asdf))
254
    asdf
255
    """
256
    cdef string b = string(a)
257
    return b.c_str().decode('utf-8')
258

259

260
@cython.test_assert_path_exists("//ReturnStatNode//PythonCapiCallNode")
261
@cython.test_fail_if_path_exists("//ReturnStatNode//AttributeNode")
262
def test_cstr_ptr_decode(char* a):
263
    """
264
    >>> print(test_cstr_ptr_decode(b_asdf))
265
    asdf
266
    """
267
    cdef string b = string(a)
268
    s = b.c_str()
269
    return s.decode('utf-8')
270

271

272
@cython.test_assert_path_exists("//PythonCapiCallNode")
273
@cython.test_fail_if_path_exists("//AttributeNode")
274
def test_decode_sliced(char* a):
275
    """
276
    >>> print(test_decode_sliced(b_asdf))
277
    sd
278
    """
279
    cdef string b = string(a)
280
    return b[1:3].decode('ascii')
281

282
@cython.test_assert_path_exists("//PythonCapiCallNode")
283
@cython.test_fail_if_path_exists("//AttributeNode")
284
def test_decode_sliced_negative(char* a):
285
    """
286
    >>> a,b,c,d = test_decode_sliced_negative(b_asdf)
287
    >>> print(a)
288
    sd
289
    >>> print(b)
290
    a
291
    >>> print(c)
292
    <BLANKLINE>
293
    >>> print(d)
294
    <BLANKLINE>
295
    """
296
    cdef string b = string(a)
297
    return b[-3:-1].decode('ascii'), b[-5:-3].decode('ascii'), b[-20:-4].decode('ascii'), b[-2:-20].decode('ascii')
298

299
@cython.test_assert_path_exists("//PythonCapiCallNode")
300
@cython.test_fail_if_path_exists("//AttributeNode")
301
def test_decode_sliced_end(char* a):
302
    """
303
    >>> a,b = test_decode_sliced_end(b_asdf)
304
    >>> print(a)
305
    asd
306
    >>> print(b)
307
    asdf
308
    """
309
    cdef string b = string(a)
310
    return b[:3].decode('ascii'), b[:42].decode('ascii')
311

312
@cython.test_assert_path_exists("//PythonCapiCallNode")
313
@cython.test_fail_if_path_exists("//AttributeNode")
314
def test_decode_sliced_end_negative(char* a):
315
    """
316
    >>> a,b,c = test_decode_sliced_end_negative(b_asdf)
317
    >>> print(a)
318
    asd
319
    >>> print(b)
320
    a
321
    >>> print(c)
322
    <BLANKLINE>
323
    """
324
    cdef string b = string(a)
325
    return b[:-1].decode('ascii'), b[:-3].decode('ascii'), b[:-4].decode('ascii')
326

327
@cython.test_assert_path_exists("//PythonCapiCallNode")
328
@cython.test_fail_if_path_exists("//AttributeNode")
329
def test_decode_sliced_start(char* a):
330
    """
331
    >>> print(test_decode_sliced_start(b_asdf))
332
    df
333
    """
334
    cdef string b = string(a)
335
    return b[2:].decode('ascii')
336

337
@cython.test_assert_path_exists("//PythonCapiCallNode")
338
@cython.test_fail_if_path_exists("//AttributeNode")
339
def test_decode_sliced_start_negative(char* a):
340
    """
341
    >>> a,b = test_decode_sliced_start_negative(b_asdf)
342
    >>> print(a)
343
    df
344
    >>> print(b)
345
    asdf
346
    """
347
    cdef string b = string(a)
348
    return b[-2:].decode('ascii'), b[-20:].decode('ascii')
349

350
def test_equals_operator(char *a, char *b):
351
    """
352
    >>> test_equals_operator(b_asdf, b_asdf)
353
    (True, False)
354
    """
355
    cdef string s = string(a)
356
    cdef string t = string(b)
357
    return t == s, t != <char *>"asdf"
358

359
def test_less_than(char *a, char *b):
360
    """
361
    >>> test_less_than(b_asdf[:-1], b_asdf)
362
    (True, True, True)
363

364
    >>> test_less_than(b_asdf[:-1], b_asdf[:-1])
365
    (False, False, True)
366
    """
367
    cdef string s = string(a)
368
    cdef string t = string(b)
369
    return (s < t, s < b, s <= b)
370

371
def test_greater_than(char *a, char *b):
372
    """
373
    >>> test_greater_than(b_asdf[:-1], b_asdf)
374
    (False, False, False)
375

376
    >>> test_greater_than(b_asdf[:-1], b_asdf[:-1])
377
    (False, False, True)
378
    """
379
    cdef string s = string(a)
380
    cdef string t = string(b)
381
    return (s > t, s > b, s >= b)
382

383

384
def test_iteration(string s):
385
    """
386
    >>> test_iteration(b'xyz')
387
    [120, 121, 122]
388
    >>> test_iteration(b'')
389
    []
390
    """
391
    return [c for c in s]
392

393

394
def test_to_string(x):
395
    """
396
    >>> print(test_to_string(5))
397
    si=5 sl=5 ss=5 sss=5
398
    >>> print(test_to_string(-5))
399
    si=-5 sl=-5 ss=5 sss=-5
400
    """
401
    si = to_string(<int>x).decode('ascii')
402
    sl = to_string(<long>x).decode('ascii')
403
    ss = to_string(<size_t>abs(x)).decode('ascii')
404
    sss = to_string(<ssize_t>x).decode('ascii')
405
    return f"si={si} sl={sl} ss={ss} sss={sss}"
406

407

408
def test_stoi(char *a):
409
    """
410
    >>> test_stoi(b'5')
411
    5
412
    """
413
    cdef string s = string(a)
414
    return stoi(s)
415

416

417
def test_stof(char *a):
418
    """
419
    >>> test_stof(b'5.5')
420
    5.5
421
    """
422
    cdef string s = string(a)
423
    return stof(s)
424

425

426
def test_swap():
427
    """
428
    >>> test_swap()
429
    """
430
    cdef string s1 = b_asdf, s_asdf = b_asdf
431
    cdef string s2 = b_asdg, s_asdg = b_asdg
432
    s1.swap(s2)
433
    assert s1 == s_asdg and s2 == s_asdf
434

435

436
def test_float_parsing(bstring):
437
    """
438
    >>> test_float_parsing(b'0.5')
439
    0.5
440
    >>> try: test_float_parsing(b'xxx')
441
    ... except ValueError: pass
442
    ... else: print("NOT RAISED!")
443
    >>> try: test_float_parsing(b'')
444
    ... except ValueError: pass
445
    ... else: print("NOT RAISED!")
446
    """
447
    cdef string s = bstring
448
    return float(s)
449

450

451
_WARNINGS = """
452
21:31: Cannot pass Python object as C++ data structure reference (string &), will pass by copy.
453
"""
454

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.