blob: 74b4fcfdf80a841aed8c446241a61757a57fb6c0 [file] [log] [blame]
Paul Sokolovsky439542f2014-01-21 00:19:19 +02001#include <stdlib.h>
2#include <stdint.h>
3#include <string.h>
4#include <assert.h>
5
6#include "nlr.h"
7#include "misc.h"
8#include "mpconfig.h"
Damien George12eacca2014-01-21 21:54:15 +00009#include "qstr.h"
Paul Sokolovsky439542f2014-01-21 00:19:19 +020010#include "obj.h"
11#include "map.h"
12#include "runtime0.h"
13#include "runtime.h"
14
15// Helpers for sequence types
16
Paul Sokolovsky87e85b72014-02-02 08:24:07 +020017#define SWAP(type, var1, var2) { type t = var2; var2 = var1; var1 = t; }
18
Paul Sokolovsky439542f2014-01-21 00:19:19 +020019// Implements backend of sequence * integer operation. Assumes elements are
20// memory-adjacent in sequence.
21void mp_seq_multiply(const void *items, uint item_sz, uint len, uint times, void *dest) {
22 for (int i = 0; i < times; i++) {
23 uint copy_sz = item_sz * len;
24 memcpy(dest, items, copy_sz);
25 dest = (char*)dest + copy_sz;
26 }
27}
Paul Sokolovsky7364af22014-02-02 02:38:22 +020028
29bool m_seq_get_fast_slice_indexes(machine_uint_t len, mp_obj_t slice, machine_uint_t *begin, machine_uint_t *end) {
30 machine_int_t start, stop, step;
31 mp_obj_slice_get(slice, &start, &stop, &step);
32 if (step != 1) {
33 return false;
34 }
35
36 // Unlike subscription, out-of-bounds slice indexes are never error
37 if (start < 0) {
38 start = len + start;
39 if (start < 0) {
40 start = 0;
41 }
42 } else if (start > len) {
43 start = len;
44 }
45 if (stop <= 0) {
46 stop = len + stop;
47 // CPython returns empty sequence in such case
48 if (stop < 0) {
49 stop = start;
50 }
51 } else if (stop > len) {
52 stop = len;
53 }
54 *begin = start;
55 *end = stop;
56 return true;
57}
Paul Sokolovsky87e85b72014-02-02 08:24:07 +020058
59// Special-case comparison function for sequences of bytes
60// Don't pass RT_BINARY_OP_NOT_EQUAL here
61bool mp_seq_cmp_bytes(int op, const byte *data1, uint len1, const byte *data2, uint len2) {
62 // Let's deal only with > & >=
63 if (op == RT_BINARY_OP_LESS || op == RT_BINARY_OP_LESS_EQUAL) {
64 SWAP(const byte*, data1, data2);
65 SWAP(uint, len1, len2);
66 if (op == RT_BINARY_OP_LESS) {
67 op = RT_BINARY_OP_MORE;
68 } else {
69 op = RT_BINARY_OP_MORE_EQUAL;
70 }
71 }
72 uint min_len = len1 < len2 ? len1 : len2;
73 int res = memcmp(data1, data2, min_len);
74 if (res < 0) {
75 return false;
76 }
77 if (res > 0) {
78 return true;
79 }
80
81 // If we had tie in the last element...
82 // ... and we have lists of different lengths...
83 if (len1 != len2) {
84 if (len1 < len2) {
85 // ... then longer list length wins (we deal only with >)
86 return false;
87 }
88 } else if (op == RT_BINARY_OP_MORE) {
89 // Otherwise, if we have strict relation, equality means failure
90 return false;
91 }
92 return true;
93}