summaryrefslogtreecommitdiff
path: root/modules/language/python/bytes.scm
blob: e3d8245b279e6c6f0cf8dff4dab425c087ebba63 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
(define-module (language python bytes)
  #:use-module (oop goops)
  #:use-module (oop pf-objects)
  #:use-module (ice-9 match)
  #:use-module (ice-9 format)
  #:use-module (ice-9 iconv)
  #:use-module (rnrs bytevectors)
  #:use-module (system foreign)
  #:use-module (language python string)
  #:use-module (language python for)
  #:use-module (language python def)
  #:use-module (language python try)
  #:use-module (language python exceptions)
  #:use-module (language python list)
  #:use-module (language python hash)
  #:use-module (language python bool)
  #:use-module (language python persist)
  #:export (<py-bytes> bv-scm pybytes-listing bytes bytearray bytes->bytevector
                       py-decode make_trans
		       <py-bytearray> pybytesarray-listing scm-bytevector))

(define (bv-scm x)
  (slot-ref (bytes x) 'bytes))

(define (scm-bytevector x)
  (slot-ref (bytes x) 'bytes))

(define (bytes->bytevector x) (slot-ref x 'bytes))
(define-syntax-rule (aif it p x y) (let ((it p)) (if it x y)))

(define b-ref   bytevector-u8-ref)
(define b-set!  bytevector-u8-set!)
(define b-make  make-bytevector)
(define b-len   bytevector-length)
(define (b->list x) (bytevector->u8-list (bv-scm x)))
(define list->b u8-list->bytevector)
(define-class <py-bytes> () bytes)
(define-class <py-bytearray> () n vec)

(name-object <py-bytes>)
(name-object <py-bytearray>)

(cpit <py-bytes> (o (lambda (o n l)
		      (slot-set! o 'bytes
				 (let lp ((l l) (i 0) (b (b-make n)))
				   (if (pair? l)
				       (b-set! b i (car l))
				       (lp (cdr l) (+ i 1) b)))))
		    (let* ((b (slot-ref o 'bytes))
			   (n (b-len b)))
		      (list
		       n
		       (let lp ((i 0))
			 (if (< i n)
			     (cons (b-ref b i) (lp (+ i 1)))
			     '()))))))

(cpit <py-bytearray> (o (lambda (o n m l)
			  (slot-set! o 'n m)
			  (slot-set! o 'vec
				     (let lp ((l l) (i 0) (b (b-make n)))
				       (if (pair? l)
					   (b-set! b i (car l))
					   (lp (cdr l) (+ i 1) b)))))
			(let* ((b (slot-ref o 'vec))
			       (n (b-len b)))
			  (list
			   n
			   (slot-ref o 'n)
			   (let lp ((i 0))
			     (if (< i n)
				 (cons (b-ref b i) (lp (+ i 1)))
				 '()))))))


(define-method (b-get (o <bytevector>))
  o)
(define-method (b-get (o <py-bytes>))
  (slot-ref o 'bytes))
(define-method (b-get (o <py-bytearray>))
  (slot-ref o 'vec))

(define (b-char x)
  (cond
   ((char? x)
    (ch-find x))
   ((string? x)
    (ch-find (string-ref x 0)))
   (else
    x)))

(define-python-class bytes (<py-bytes>)
  (define maketrans
    (lambda (x y) (make_trans x y)))
  
  (define __init__
    (case-lambda
     ((self)
      (__init__ self ""))
     ((self s)
       (cond
        ((is-a? s <string>)
         (let* ((n    (string-length s))
                (bytes  (b-make n)))
           (let lp ((i 0))
             (if (< i n)
                 (begin
                   (b-set! bytes i (ch-find (string-ref s i)))
                   (lp (+ i 1)))))
           (slot-set! self 'bytes bytes)))
        ((is-a? s <py-string>)
         (__init__ self (slot-ref s 'str)))        
        ((is-a? s <py-bytes>)
         (slot-set! self 'bytes (slot-ref s 'bytes)))
        ((is-a? s <bytevector>)
         (slot-set! self 'bytes s))
        ((is-a? s <py-bytearray>)
         (let* ((n (slot-ref s 'n))
                (b (b-make n)))
           (bytevector-copy! (slot-ref s 'vec) 0 b 0 n)
           (slot-set! self 'bytes b)))
        (else
         (for ((x : s)) ((r '()))
              (cons (b-char x) r)
              
              #:final
              (let* ((n     (length r))
                     (bytes (b-make n)))
                (let lp ((i (- n 1)) (r r))
                  (if (>= i 0)
                      (begin
                        (b-set! bytes i (car r))
                        (lp (- i 1) (cdr r)))
                      (slot-set! self 'bytes bytes)))))))))))

(name-object bytes)

(define-python-class bytearray (<py-bytearray>)
  (define __init__
    (case-lambda
     ((self)
      (__init__ self ""))
     ((self s)
      (cond
       ((is-a? s <string>)
	(let* ((n     (string-length s))
	       (bytes (b-make n)))
	  (let lp ((i 0))
	    (if (< i n)
		(begin
		  (b-set! bytes i (ch-find (string-ref s i)))
		  (lp (+ i 1)))))
	  (slot-set! self 'vec bytes)
	  (slot-set! self 'n   n)))
       ((is-a? s <py-string>)
	(__init__ self (slot-ref s 'str)))        
       ((is-a? s <py-bytes>)
	(let ((b (slot-ref s 'bytes)))
	  (slot-set! self 'vec (bytevector-copy b))
	  (slot-set! self 'n   (b-len b))))
       ((is-a? s <bytevector>)
	(slot-set! self 'vec (bytevector-copy s))
	(slot-set! self 'n   (b-len s)))
       ((is-a? s <py-bytearray>)
	(slot-set! self 'vec (bytevector-copy (slot-ref s 'vec)))
	(slot-set! self 'n   (slot-ref s 'n)))
       (else        
	(for ((x : s)) ((r '()))
	     (cons (b-char x) r)
	     #:final
	     (let* ((n   (length r))
		    (bytes (b-make n)))
	       (let lp ((i (- n 1)) (r r))
		 (if (>= i 0)
		     (begin
		       (b-set! bytes i (car r))
		       (lp (- i 1) (cdr r)))
		     (begin
		       (slot-set! self 'vec bytes)
		       (slot-set! self 'n (b-len bytes)))))))))))))

(name-object bytearray)

(define-syntax-rule (define-py (f o . u) code ...)
  (begin
    (define-method (f (o <bytevector>) . u) code ...)
    (define-method (f (o <py-bytes>)     . l) (apply f (slot-ref o 'bytes) l))))

(define-syntax-rule (define-py! (f o . u) code ...)
  (begin
    (define-method (f (o <py-bytearray>) . u) code ...)))

(define (idd x) x)
(define-syntax-rule (define-py* g (f m o nn . u) code ...)
  (begin
    (define (g m o nn . u) code ...)
    (define-method (f (o <bytevector>) . l)
      (apply g idd o (b-len o) l))
    (define-method (f (o <py-bytes>) . l)
      (let ((b (slot-ref o 'bytes)))
        (apply g bytes b (b-len b) l)))
    (define-method (f (o <py-bytearray>) . l)
      (let ((b (slot-ref o 'vec))
            (n (slot-ref o 'n)))
        (apply g bytearray b n l)))))

(define-syntax-rule (define-py** g (f m o nn . u) code ...)
  (begin
    (define (g m o nn . u) code ...)
    (define-method (f (o <bytevector>) . l)
      (apply g idd o (b-len o) l))
    (define-method (f (o <py-bytes>) . l)
      (let ((b (slot-ref o 'bytes)))
        (apply g bytes b (b-len b) l)))
    (define-method (f (o <py-bytearray>) . l)
      (let ((b (slot-ref o 'vec))
            (n (slot-ref o 'n)))
        (apply g bytearray b n l)))
    (define-method (f (o <p>) . l)
      (aif it (ref o 'g)
           (apply it l)
           (next-method)))))

(define-py* -bool (bool m o nn) (if (= (len o) 0) #f o))

(define-method (write (b <py-bytes>) . l)
  (define port (if (pair? l) (car l) #t))
  (format port "b'")
  (b->string port (slot-ref b 'bytes))
  (format port "'"))

(define-method (write (b <py-bytearray>) . l)
  (define port (if (pair? l) (car l) #t))
  (format port "bytearray(b'")
  (b->string port (pylist-slice (slot-ref b 'vec) 0 (len b) 1))
  (format port "')"))


(define dynlink (dynamic-link))

(define stringn
  (pointer->procedure
   '*
   (dynamic-func "scm_from_latin1_stringn" dynlink)
   (list '* size_t)))

(define ch->i (make-hash-table))

(define (re-eval ch)
  (let lp ((i 0))
    (if (< i 256)
        (if (eq? ch (chf i))
            (begin
              (hash-set! ch->i ch i)
              (lp (+ i 1)))
            (lp (+ i 1)))
        (hash-ref ch->i ch))))

(define (ch-find ch)
  (aif it (hash-ref ch->i ch #f)
       (if (eq? ch (chf it))
           it
           (re-eval ch))
       (re-eval ch)))

(define (chf ch)
  (let ((bytes (pointer->scm
              (stringn
               (bytevector->pointer
                (b-make 1 ch))
               1))))
    (if (= (string-length bytes) 1)
        (string-ref bytes 0)
        (chf 0))))

(define (b->string port b)
  (let ((n (b-len b)))
    (let lp ((i 0))
      (if (< i n)
	  (let ((ch (b-ref b i)))
	    (cond
	     ((equal? ch 0)
	      (format port "\\x00"))
	     ((equal? (chf ch) #\\)
	      (format port "\\\\"))
	     ((equal? (chf ch) #\')
	      (format port "\\'"))
	     ((equal? (chf ch) #\newline)
	      (format port "\\n"))
	     ((= ch 7)
	      (format port "\\a"))
	     ((= ch 8)
	      (format port "\\b"))
	     ((= ch 12)
	      (format port "\\f"))
	     ((= ch 10)
	      (format port "\\n"))
	     ((= ch 13)
	      (format port "\\r"))
	     ((= ch 9)
	      (format port "\\t"))
	     ((= ch 11)
	      (format port "\\v"))
	     (else
	      (if (< ch 32)		  
		  (format port "\\x~2,'0x" ch)
		  (format port "~a"      (make-string 1 (chf ch))))))
	    (lp (+ i 1)))))))

(define-py  (py-hash b) (hash b pyhash-N))

(define-py* pylist (pylist-ref bytes o N nin)
  (define n (if (< nin 0) (+ N nin) nin))
  (if (and (>= n 0) (< n N))
      (if (eq? bytes idd)
	  (b-ref o n)
	  (bytes (b-make 1 (b-ref o n))))
      (raise IndexError)))

(define-py  (len b) (b-len b))
(define-py! (len b) (slot-ref b 'n))

(define-py* ->list (to-list mk b n)
  (let lp ((i 0) (r '()))
    (if (< i n)
        (lp (+ i 1) (cons (b-ref b i) r))
        (reverse r))))

(define-py* ->pylist (to-pylist mk b n)
  (let* ((m n)
         (o (make <py-list>))
         (v (make-vector m)))
    (slot-set! o 'vec v)
    (slot-set! o 'n   n)
    (let lp ((i 0))
      (if (< i n)
          (begin
            (vector-set! v i (if (equal? bytes idd)
				 (b-ref b i)
				 (bytes (b-make 1 (b-ref b i)))))
            (lp (+ i 1)))
          o))))
  

(define-py! (pylist-set! o nin val)
  (define N (slot-ref o 'n))
  (define n (if (< nin 0) (+ N nin) nin))    
  (if (and (>= n 0) (< n (slot-ref o 'n)))
      (b-set! (slot-ref o 'vec) n val)
      (raise IndexError)))

(define-py* slice (pylist-slice bytes o N n1 n2 n3)
  (define (f n) (max 0 (min N (if (< n 0) (+ N n) n))))
    
  (let* ((n1   (f (if (eq? n1 None) 0 n1)))
         (n2   (f (if (eq? n2 None) N n2)))
         (n3   (f (if (eq? n3 None) 1 n3)))
         (n    (let lp ((i n1) (j 0))
                 (if (< i n2)
                     (lp (+ i n3) (+ j 1))
                     j)))
         (b    (b-make n)))
    (let lp ((i n1) (j 0))
      (if (< j n)
          (begin
            (b-set! b j (b-ref o i))
            (lp (+ i n3) (+ j 1)))
          (bytes b)))))

(define-py! (pylist-subset! o n1 n2 n3 val)
  (define N (slot-ref o 'n))
  (define (f n) (if (< n 0) (+ N n) n))
  
  (let* ((n1   (f (if (eq? n1 None) 0                n1)))
         (n2   (f (if (eq? n2 None) (slot-ref o 'n)  n2)))
         (n3   (f (if (eq? n3 None) 1                n3)))         
         (vec  (slot-ref o 'vec))
         (l2   (to-list val))    
         (N2   (length l2)))
    (if (<= n2 N)
        (let lp ((i 0) (l2 l2)  (j n1))
          (if (< j n2)
              (if (< i N2)
                  (let ((r (car l2)))
                    (if (and (number? r) (integer? r) (>= r 0) (< r 256))
                        (begin
                          (b-set! vec j r)
                          (lp (+ i 1) (cdr l2) (+ j n3)))
                        (raise TypeError "not a byte")))
                  (let lp ((j2 j))
                    (if (< j2 n2)
                        (lp (+ j2 n3))
                        (let lp ((k1 j) (k2 j2))
                          (if (< k2 N)
                              (begin
                                (b-set! vec k1 (b-ref vec k2))
                                (lp (+ k1 1) (+ k2 1)))
                              (begin
                                (let lp ((i k2))
                                  (if (< i N)
                                      (begin
                                        (b-set! vec i #f)
                                        (lp (+ i 1)))
                                      (slot-set! o 'n k1)))))))))))
        (raise IndexError))
    (values)))

(define (byte x)
  (or (and (integer? x) (>= x 0) (< x 256) x)
      (and (is-a? x <bytevector>)   (b-ref x 0))
      (and (is-a? x <py-bytes>)     (b-ref (slot-ref x 'bytes) 0))
      (and (is-a? x <py-bytearray>) (b-ref (slot-ref x 'vec)   0))))
      
(define-py! (pylist-append! o val)
  (let* ((n   (slot-ref o 'n))
         (vec (slot-ref o 'vec))
	 (N   (b-len vec)))
    (aif v (byte val)
         (begin
           (if (< n N)
	       (b-set! vec n v)
               (let* ((N    (* 2 N))
                      (vec2 (b-make N)))
                 (let lp ((i 0))
                   (if (< i n)
                       (begin
                         (b-set! vec2 i (b-ref vec i))
                         (lp (+ i 1)))))
                 (b-set! vec2 n v)
                 (slot-set! o 'vec vec2)))
           (slot-set! o 'n (+ n 1))
           (values))
         (raise TypeError "not a byte" val))))

  
(define (b-concat b1 n1 b2 n2)
  (let* ((n  (+ n1 n2))
         (b  (b-make n)))
    (let lp ((i 0))
      (if (< i n1)
          (begin
            (b-set! b i (b-ref b1 i))
            (lp (+ i 1)))
          (let lp ((i i) (j 0))
	    (if (< j n2)
		(begin
		  (b-set! b i (b-ref b2 j))
		  (lp (+ i 1) (+ j 1)))
		b))))))

(define-method (+ (o1 <py-bytes>) (b2 <bytevector>))
  (let* ((b1 (slot-ref o1 'bytes))
         (n1 (b-len b1))
         (n2 (b-len b2))
         (o  (make <py-bytes>))
         (b  (b-concat b1 n1 b2 n2)))
    (slot-set! o 'bytes b)
    o))

(define-method (+ (b2 <bytevector>) (o1 <py-bytes>))
  (let* ((b1 (slot-ref o1 'bytes))
         (n1 (b-len b1))
         (n2 (b-len b2))
         (o  (make <py-bytes>))
         (b  (b-concat b2 n2 b1 n1)))
    (slot-set! o 'bytes b)
    o))

(define-method (+ (b1 <bytevector>) (b2 <bytevector>))
  (let* ((n1 (b-len b1))
         (n2 (b-len b2)))
    (b-concat b1 n1 b2 n2)))

(define-method (+ (o1 <py-bytes>) (o2 <py-bytes>))
  (let* ((b1 (slot-ref o1 'bytes))
         (b2 (slot-ref o2 'bytes))
         (n1 (b-len b1))
         (n2 (b-len b2))
         (o  (make <py-bytes>))
         (b  (b-concat b1 n1 b2 n2)))
    (slot-set! o 'bytes b)
    o))

(define-method (+ (o1 <py-bytearray>) (o2 <py-bytes>))
  (let* ((b1 (slot-ref o1 'vec))
         (b2 (slot-ref o2 'bytes))
         (n1 (slot-ref o1 'n))
         (n2 (b-len b2))
         (o  (make <py-bytearray>))
         (b  (b-concat b1 n1 b2 n2)))
    (slot-set! o 'vec b)
    (slot-set! o 'n   (+ n1 n2))
    o))

(define-method (+ (o1 <py-bytearray>) (b2 <bytevector>))
  (let* ((b1 (slot-ref o1 'vec))
         (n1 (slot-ref o1 'n))
         (n2 (b-len b2))
         (o  (make <py-bytearray>))
         (b  (b-concat b1 n1 b2 n2)))
    (slot-set! o 'vec b)
    (slot-set! o 'n   (+ n1 n2))
    o))

(define-method (+ (o2 <py-bytes>) (o1 <py-bytearray>))
  (let* ((b1 (slot-ref o1 'vec))
         (b2 (slot-ref o2 'bytes))
         (n1 (slot-ref o1 'n))
         (n2 (b-len b2))
         (o  (make <py-bytearray>))
         (b  (b-concat b2 n2 b1 n1)))
    (slot-set! o 'vec b)
    (slot-set! o 'n   (+ n1 n2))
    o))

(define-method (+ (b2 <bytevector>) (o1 <py-bytearray>) )
  (let* ((b1 (slot-ref o1 'vec))
         (n1 (slot-ref o1 'n))
         (n2 (b-len b2))
         (o  (make <py-bytearray>))
         (b  (b-concat b2 n2 b1 n1)))
    (slot-set! o 'vec b)
    (slot-set! o 'n   (+ n1 n2))
    o))

(define-method (+ (o1 <py-bytearray>) (o2 <py-bytearray>))
  (let* ((b1 (slot-ref o1 'vec))
         (b2 (slot-ref o2 'vec))
         (n1 (slot-ref o1 'n))
         (n2 (slot-ref o2 'n))
         (o  (make <py-bytearray>))
         (b  (b-concat b1 n1 b2 n2)))
    (slot-set! o 'vec b)
    (slot-set! o 'n   (+ n1 n2))
    o))

(define (b-rep b n m)
  (let* ((N (* n m))
         (r (b-make N)))
    (let lp ((i 0) (j 0))
      (if (< i m)
          (let lp2 ((j j) (k 0))
            (if (< k n)
                (begin
                  (b-set! r j (b-ref b k))
                  (lp2 (+ j 1) (+ k 1)))
                (lp (+ i 1) j)))
          r))))

(define-method (* (o1 <py-bytearray>) m)
  (let* ((b1 (slot-ref o1 'vec))
         (n1 (slot-ref o1 'n))
         (o  (make <py-bytearray>))
         (b  (b-rep b1 n1 m)))
    (slot-set! o 'vec b)
    (slot-set! o 'n (* n1 m))
    o))

(define-method (* (b1 <bytevector>) m)
  (let* ((n1 (b-len b1)))
    (b-rep b1 n1 m)))

(define-method (* (o1 <py-bytes>) m)
  (let* ((b1 (slot-ref o1 'bytes))
         (n1 (b-len b1))
         (o  (make <py-bytes>))
         (b  (b-rep b1 n1 m)))
    (slot-set! o 'bytes b)
    o))

(define-py* cap (py-capitalize bytes s n)
  (let* ((w (b-make n)))
    (let lp ((i 0) (first? #t))
      (if (< i n)
          (let* ((x  (b-ref s i))
                 (ch (chf x)))
            (define (f first?)
              (b-set! w i x)
              (lp (+ i 1) first?))
            
            (if (and first? (char-alphabetic? ch))
                (aif it (ch-find (char-upcase ch))
                     (begin
                       (b-set! w i it) 
                       (lp (+ i 1) #f))
                     (f #t))
                (f #f)))
          (bytes w)))))

(define-py* center (py-center bytes o n w . l)
  (let* ((ws (if (pair? l)
                 (ch-find (b-ref (car l) 0))
                 (ch-find #\space)))
         (w  (if (< w n) n w))
         (d  (- w n))
         (e  (floor-quotient (- w n) 2))
         (s  (b-make w (ch-find #\space))))
    (let lp ((i 0) (j e))
      (if (< i n)
          (begin
            (b-set! s j (b-ref o i))
            (lp (+ i 1) (+ j 1)))))
    (bytes s)))

(define-python-class UnicodeDecodeError (Exception))

(define-py** decode (py-decode bytes o n . l)
  (apply
   (lam ((= encoding "UTF-8") (= errors "strict"))	
	(set! errors   (py-lower (scm-str errors)))
	(set! errors   (cond
			((equal? errors "strict")
			 'error)
			((equal? errors "escape")
			 'escape)
			((equal? errors "replace")
			 'substitute)
			((equal? errors "ignore")
			 (warn
			  (string-append
			   "not possible to use ignore "
			   "encodong error strategy "
			   "using replace in stead"))
			 'substitute)
			(else
			 (warn
			  "not a correct encodong error strategy")
			 'error)))
	(set! encoding (py-upper (scm-str encoding)))
	
	(let lp ((i 0) (r '()))
	  (if (< i n)
	      (lp (+ i 1) (cons (b-ref o i) r))
	      (catch #t
		(lambda ()
		  (bytevector->string
		   (list->b (reverse r))
		   encoding
		   errors))
		(lambda x
		  (raise (UnicodeDecodeError
			  (+
			   "failed to decode "
			   encoding))))))))
   l))
			     
;;;py-encode

(define-py* endswith (py-endswith bytes o n suff . l)
  (let* ((suff (slot-ref (bytes suff) 'bytes))
         (ns   (b-len suff))
         (f    (lambda (x) (< x 0) (+ n x) x)))
    (call-with-values (lambda ()
                        (match l
                          (()    (values 0      n  ))
                          ((x)   (values (f x)  n  ))
                          ((x y) (values (f x) (f y)))))
      (lambda (start end)
        (let lp ((i (- n ns)) (j 0))
          (if (< i start)
              (lp (+ i 1) (+ j 1))
              (if (>= i end)
                  #t
                  (and
                   (eq? (b-ref o i) (b-ref suff j))
                   (lp (+ i 1) (+ j 1))))))))))

(define-py* startswith (py-startswith bytes o n pre . l)
  (let* ((pre (slot-ref (bytes pre) 'bytes))
         (pre (b-get pre))
         (ns  (len pre))
         (f   (lambda (x) (< x 0) (+ n x) x)))
    (call-with-values (lambda ()
                        (match l
                          (()    (values 0      n  ))
                          ((x)   (values (f x)  n  ))
                          ((x y) (values (f x) (f y)))))
      (lambda (start end)
        (let lp ((i 0))
          (cond
           ((or (>= i end)
                (>= i ns))
            #t)
           ((< i start)
            (lp (+ i 1)))
           (else
            (and
             (eq? (b-ref o i) (b-ref pre i))
             (lp (+ i 1))))))))))


(define-py* expand (py-expandtabs bytes s n . l)
  (let* ((tabsize (match l (() 8) ((x) x)))
         (ct      (ch-find #\tab))
         (cs      (ch-find #\space))
         (n       (b-len s)))
    (let lp ((i 0) (r '()))
      (if (< i n)
          (let ((x (b-ref s i)))
            (if (eq? x ct)
                (let lp2 ((j 0) (r r))
                  (if (< j tabsize)
                      (lp2 (+ j 1) (cons cs r))
                      (lp (+ i 1) r)))
                (lp (+ i 1) (cons x r))))
          (bytes (reverse r))))))

(define (b-contains s sub nsub start end)
  (define (match i)
    (let lp ((i i) (j 0))
      (if (and (< j nsub) (< i end))
          (if (eq? (b-ref s i) (b-ref sub j))
              (lp (+ i 1) (+ j 1))
              #f)
          #t)))
  
  (let lp ((i (max start 0)))
    (if (< i end)
        (if (match i)
            i
            (lp (+ i 1)))
        #f)))

(define-py* find (py-find bytes s n sub . l)
  (let* ((f   (lambda (x) (< x 0) (+ n x) x)))
    (call-with-values (lambda ()
                        (match l
                          (()    (values 0      n  ))
                          ((x)   (values (f x)  n  ))
                          ((x y) (values (f x) (f y)))))
      (lambda (start end)
        (let ((sub (b-get sub)))
        (aif it (b-contains s sub (len sub) start end)
             it
             -1))))))

(define (b-reverse s n)
  (if (is-a? s (<py-bytes>))
      (b-reverse (slot-ref s 'bytes) n)
      (let* ((r (b-make n)))
        (let lp ((i 0) (j (- n 1)))
          (if (< i n)
              (begin
                (b-set! r j (b-ref s i))
                (lp (+ i 1) (- j 1)))
              r)))))
         

(define-py* rfind (py-rfind bytes s n sub . l)  
  (let* ((sub (slot-ref (bytes sub) 'bytes))
         (s    (b-reverse s n))
         (nsub (len sub))
         (sub (b-reverse (b-get sub) nsub))
         (f   (lambda (x) (< x 0) (+ n x) x)))
    (call-with-values (lambda ()
                        (match l
                          (()    (values 0      n  ))
                          ((x)   (values (f x)  n  ))
                          ((x y) (values (f x) (f y)))))
      (lambda (start end)
        (aif it (b-contains s sub nsub start end)
             (- n it nsub)
             -1)))))

#|
(define i       (f-list #:i (mk-token (f+ (f-reg! "[0-9]")))))
(define s       (f-list #:s (mk-token (f+ (f-not! (f-tag "}"))))))
(define e       (f-list #:e (f-and (f-tag "}") f-true)))
(define tagbody (f-or! e i s))

(define tag     (f-seq "{" tagbody "}"))
(define nontag  (f-list #:bytes (mk-token (f+  (f-or! (f-tag "{{") 
                                                    (f-not! tag))))))
(define e       (ff* (f-or! tag nontag)))

(define (compile x args kwargs)
  (let lp ((l x) (r '()) (u '()) (i 0))
    (match l
      (((#:bytes x) . l)
       (lp l (cons x r) u i))
      (((#:i x)   . l)
       (lp l (cons "~a" r) (cons (list-ref args (string->number x)) u) i))
      (((#:s x)   . l)
       (lp l (cons "~a" r) (cons (hash-ref kwargs x None) u) i))
      (((#:e)     . l)
       (lp l (cons "~a" r) (cons (list-ref args i) u) (+ i 1)))
      (()
       (apply format #f (string-join (reverse r) "") (reverse u))))))

(define-py (py-format format s . l)
  (call-with-values
      (lambda ()
        (let lp ((l l) (args '()) (kwargs (make-hash-table)))
          (match l
            (((? keyword? key) x . l)
             (hash-set! kwargs (symbol->string (keyword->symbol key)) x)
             (lp l args kwargs))
            ((x . l)
             (lp l (cons x args) kwargs))
            (()
             (values (reverse args) kwargs)))))
    (lambda (args kwargs)
      (compile (parse s e) args kwargs))))
|#

(define-syntax-rule (mk-is py-isalnum x ...)
  (define-py* isalnum (py-isalnum bytes s n)
    (let lp ((i 0))
      (if (< i n)
          (let ((ch (chf (b-ref s i))))
            (if (or (x ch) ...)
                (lp (+ i 1))
                #f))
          #t))))

(mk-is py-isalnum char-alphabetic? char-numeric?)
(mk-is py-isalpha char-alphabetic?)
(mk-is py-isdigit char-numeric?)
(mk-is py-islower char-lower-case?)
(mk-is py-isspace char-whitespace?)
(mk-is py-isupper char-upper-case?)


(define-py* istitle (py-istitle bytes s n)
  (if ((> n 0))
      (let lp ((i 0) (space? #t))
        (if (< i n)
            (let ((ch (chf (b-ref s i))))
              (if space?
                  (cond
                   ((char-whitespace? ch)
                    (lp (+ i 1) #t))
                   ((char-upper-case? ch)
                    (lp (+ i 1) #f))
                   (else
                    #f))
                  (cond
                   ((char-whitespace? ch)
                    (lp (+ i 1) #t))
                   ((char-upper-case? ch)
                    #f)
                   ((char-lower-case? ch)
                    (lp (+ i 1) #f))
                   (else
                    #f))))
            #t))
      #f))

(define (b-join bytes l s ns)
  (let* ((n  (let lp ((l l) (n 0))
               (if (pair? l)
                   (let ((x (car l))
                         (l (cdr l)))
                     (lp l (+ n (len x) (if (pair? l) ns 0))))
                   n)))
         (r  (b-make n)))
    (let lp ((l l) (i 0))
      (if (pair? l)
          (let* ((x (car l))
                 (n (len x))
                 (x (b-get x))
                 (l (cdr l)))
            (let lp2 ((j 0) (i i))
              (if (< j n)
                  (begin
                    (b-set! r i (b-ref x j))
                    (lp2 (+ j 1) (+ i 1)))
                  (if (pair? l)
                      (let lp3 ((j 0) (i i))
                        (if (< j ns)
                            (begin
                              (b-set! r i (b-ref s j))
                              (lp3 (+ j 1) (+ i 1)))
                            (lp l i)))
                      (lp l i)))))
          (bytes r)))))

(define-py* join (py-join bytes s n iterator)
  (b-join bytes (to-list iterator) s n))
            
(define-py* ljust (py-ljust bytes s n width . l)
  (let* ((ch (match l
               ((x)
                (b-char x))
               (()
                (b-char #\space)))))
    (if (< width n)
        (pylist-slice s 0 width 1)
        (let ((ret (b-make width ch)))
          (let lp ((i 0))
            (if (< i n)
                (begin
                  (b-set! ret i (b-ref s i))
                  (lp (+ i 1)))
                (bytes ret)))))))

(define-py* rjust (py-rjust bytes s n width . l)
  (let* ((ch (match l
               ((x)
                (b-char x))
               (()
                (b-char #\space)))))
    (if (< width n)
        (pylist-slice s (- width) (len s) 1)
        (let ((ret (b-make width ch)))
          (let lp ((i 0) (j (- width n)))
            (if (< i n)
                (begin
                  (b-set! ret j (b-ref s i))
                  (lp (+ i 1) (+ j 1)))
                (bytes ret)))))))


(define-py* lower (py-lower bytes s n)
  (let* ((r (b-make n)))
    (let lp ((i 0))
      (if (< i n)
          (let* ((x  (b-ref s i))
                 (ch (chf x)))
            (b-set! r i (if (char-upper-case? ch)
                            (ch-find (char-downcase ch))
                            x))
            (lp (+ i 1)))
          (bytes r)))))

(define-py* upper (py-upper bytes s n)
  (let* ((r (b-make n)))
    (let lp ((i 0))
      (if (< i n)
          (let* ((x  (b-ref s i))
                 (ch (chf x)))
            (b-set! r i (if (char-lower-case? ch)
                            (ch-find (char-upcase ch))
                            x))
            (lp (+ i 1)))
          (bytes r)))))

(define-py* swapcase (py-swapcase bytes s n)
  (let* ((r (b-make n)))
    (let lp ((i 0))
      (if (< i n)
          (let* ((x  (b-ref s i))
                 (ch (chf x)))
            (b-set! r i (cond
                         ((char-lower-case? ch)
                          (ch-find (char-upcase ch)))
                         ((char-upper-case? ch)
                          (ch-find (char-downcase ch)))
                         (else
                          x)))
            (lp (+ i 1)))
          (bytes r)))))

(define b-trim
  (case-lambda
    ((bytes s n)
     (b-trim bytes s n (lambda (ch x) (char-whitespace? ch))))
    ((bytes s n p)
     (let lp ((i 0) (r '()) (first? #t))
       (if (< i n)
           (let ((x (b-ref s i)))
             (if first?
                 (if (p (chf x) x)
                     (lp (+ i 1) r #t)
                     (lp (+ i 1) (cons x r) #f))
                 (lp (+ i 1) (cons x r) #f)))
           (bytes (reverse r)))))))

(define b-rtrim
  (case-lambda
    ((bytes s n)
     (b-rtrim bytes s n (lambda (ch x) (char-whitespace? ch))))
    ((bytes s n p)
     (let lp ((i (- n 1)) (r '()) (first? #t))
       (if (>= i 0)
           (let ((x (b-ref s i)))
             (if first?
                 (if (p (chf x) x)
                     (lp (- i 1) r #t)
                     (lp (- i 1) (cons x r) #f))
                 (lp (- i 1) (cons x r) #f)))
           (bytes r))))))

(define-py* lstrip (py-lstrip bytes s n . l)
  (match l
    (()
     (b-trim bytes s n))
    ((x)
     (let ((l (map b-char (to-list x))))
       (b-trim bytes s n (lambda (ch x) (member x l)))))))

(define-py* restrip (py-rstrip bytes s n . l)
  (match l
    (()
     (b-rtrim bytes s n))
    ((x)
     (let ((l (map b-char (to-list x))))
       (b-rtrim bytes s n (lambda (ch x) (member x l)))))))


(define-py* partition (py-partition bytes s n sep)
  (let* ((sep (b-get sep))
         (m   (b-len sep)))
    (define (test i)
      (let lp ((i i) (j 0))
        (if (< i n)
            (if (< j m)
                (if (eq? (b-ref s i) (b-ref sep j))
                    (lp (+ i 1) (+ j 1))
                    #f)
                #t)
            #f)))
    (let lp ((i 0))
      (if (< i n)
          (if (test i)
              (list (pylist-slice s 0 i) sep (pylist-slice s (+ i m) n))
              (lp (+ i 1)))
          (list s "" "")))))

(define-py* rpartition (py-rpartition bytes ss n ssep)
  (let* ((s    (b-reverse ss n))
         (m    (len ssep))
         (sep  (b-reverse (b-get ssep) m)))
    (define (test i)
      (let lp ((i i) (j 0))
        (if (< i n)
            (if (< j m)
                (if (eq? (b-ref s i) (b-ref sep j))
                    (lp (+ i 1) (+ j 1))
                    #f)
                #t)
            #f)))
    (let lp ((i 0))
      (if (< i n)
          (if (test i)
              (list (bytes
                     (b-reverse
                      (pylist-slice s (+ i m) n)
                      (- n (+ i m))))
                    (bytes sep)
                    (bytes
                     (b-reverse
                      (pylist-slice s 0 i)
                      i)))
              (lp (+ i 1)))
          (list (bytes "") (bytes "") s)))))

(define-py* replace (py-replace bytes s n old new . l)
  (let ((n (match l (() #f) ((n . _) n))))
    (b-join
     bytes
     (reverse
      (let lp ((s s) (r '()))
        (let ((l (py-partition s old)))
          (if (equal? (cadr l) "")
              (cons s r)
              (lp (list-ref l 2) (cons (car l) r))))))
     n
     new)))

(define-py (py-stripip s . l)
  (apply py-rstrip (apply py-lstrip s l) l))

(define-py! (py-stripip s . l)
  (apply py-rstrip (apply py-lstrip s l) l))

(define-py* index (pylist-index bytes o n val . l)
  (let* ((vec o)
         (f   (lambda (m) (if (< m 0) (+ m n) m))))
    (call-with-values
        (lambda ()
          (match l
            (()
             (values 0 n))
            ((x)
             (values (f x) n))
            ((x y)
             (values (f x) (f y)))))
      (lambda (n1 n2)
        (if (and (>= n1 0) (>= n2 0) (< n1 n) (<= n2 n))
            (let lp ((i n1))
              (if (< i n2)
                  (let ((r (b-ref vec i)))
                    (if (equal? r val)
                        i
                        (lp (+ i 1))))
                  (raise ValueError "could not find value in index fkn")))
            (raise IndexError "index out of scop in index fkn"))))))

(define-py* rindex (py-rindex býtes s n . l) 
  (let ((n (b-len s)))
    (- n (apply pylist-index (b-reverse s n) l) 1)))

#;
(define-py (py-title title s)
  (string-titlecase s))

(define-py* split (py-split bytes o n tag)
  (let ((tag (b->list tag)))
    (let lp ((i 0) (r '()))
      (if (< i n)
          (if (eq? (car tag) (b-ref o i))
              (let lp2 ((j i) (tag tag))
                (if (null? tag)
                    (cons (bytes (list->b (reverse r)))
                          (lp (+ i 1) '()))
                    (if (< j n)
                        (if (eq? (car tag) (b-ref o j))
                            (lp2 (+ j 1) (cdr tag))
                            (lp (+ i 1) (cons (b-ref o i) r)))
                        (lp (+ i 1) (cons (b-ref o i) r)))))
              (lp (+ i 1) (cons (b-ref o i) r)))
          '()))))
#;
(define-py (py-rsplit s . l)
  (reverse
   (map string-reverse
        (apply py-split
               (string-reverse s)
               (match l
                 (() '())
                 ((sep . l) (cons (string-reverse sep) l)))))))


(define-py* splitlines (py-splitlines bytes s n . l)
  (let ((keep? (match l
                 ((#:keepends v)
                  v)
                 ((v)
                  v)
                 (_ #f))))
    (let lp ((i 0) (r '()) (old 0))
      (if (< i n)
          (let* ((x  (b-ref s i))
                 (ch (chf x)))
            (if (eq? ch #\newline)
                (if keep?
                    (lp (+ i 1)
                        (cons
                         (pylist-slice s old (+ i 1) 1)
                         r)
                        (+ i 1))
                    (lp (+ i 1)
                        (cons
                         (pylist-slice s old i 1)
                         r)
                        (+ i 1)))
                (lp (+ i 1) r old)))
          (reverse r)))))

(define (make_trans b1 b2)
  (let* ((b1 (bv-scm b1))
         (b2 (bv-scm b2))
         (n1 (len b1))
         (n2 (len b2))
         (n  (let lp ((i 0) (r 0))
               (if (< i n1)
                   (lp (+ i 1) (max (bytevector-u8-ref b1 i) r))
                   r))))
    (if (= n1 n2)
        (let lp ((i 0) (r '()))      
          (if (< i n)
              (let lp2 ((j 0))
                (if (< j n1)
                    (if (= (bytevector-u8-ref b1 j) i)
                        (lp (+ i 1) (cons (bytevector-u8-ref b2 j) r))
                        (lp2 (+ j 1)))
                    (lp (+ i 1) (cons i  r))))
              (bytes (list->u8vector (reverse r)))))
        (raise
         (ValueError
          "maketrans: wrong number in second string compared to first")))))

(define-py* translate (py-translate bytes s n table . l)
  (let* ((table (b-get table))
         (w (b-make n))
         (t (if (eq? table None) #f table))
         (d (match l (() #f) ((x) (map b-char (to-list x))))))
    (define (tr ch)
      (define (e)
        (if t
            (if (< ch (b-len t))
                (b-ref t ch)
                ch)
            ch))

      (if d
          (if (member ch d)
              #f
              (e))
          (e)))
    
    (let lp ((i 0) (k 0))
      (if (< i n)
          (let ((ch (tr (b-ref s i))))
            (if ch
                (begin
                  (b-set! w k ch)
                  (lp (+ i 1) (+ k 1)))
                (lp (+ i 1) k)))
          (bytes
           (if (= k n)
               w
               (pylist-slice w 0 k 1)))))))

(define-syntax-rule (a b x y) (b (symbol->string x) (symbol->string y)))

(define (cmp op s1 n1 s2 n2)
  (let ((n (min n1 n2)))
    (let lp ((i 0))
      (if (< i n)
	  (let ((x1 (b-ref s1 i))
		(x2 (b-ref s2 i)))
	    (if (= x1 x2)
		(lp (+ i 1))
		(op x1 x2)))
	  (op n1 n2)))))


(define-syntax-rule (mkop op)
 (begin
   (define-method (op (b1 <bytevector>) (s2 <py-bytes>))
     (let ((b2 (slot-ref s2 'bytes)))
       (cmp op b1 (b-len b1) b2 (b-len b2))))
   (define-method (op (s1 <py-bytes>) (b2 <bytevector>) )
     (let ((b1 (slot-ref s1 'bytes)))
       (cmp op b1 (b-len b1) b2 (b-len b2))))
   (define-method (op (b1 <bytevector>) (b2 <bytevector>) )
     (cmp op b1 (b-len b1) b2 (b-len b2)))
   (define-method (op (s1 <py-bytes>) (s2 <py-bytes>) )
     (let ((b1 (slot-ref s1 'bytes))
	   (b2 (slot-ref s2 'bytes)))
       (cmp op b1 (b-len b1) b2 (b-len b2))))
   (define-method (op (a1 <py-bytearray>) (b2 <bytevector>))
     (let ((b1 (slot-ref a1 'vec))
	   (n1 (slot-ref a1 'n)))
       (cmp op b1 n1 b2 (b-len b2))))
   (define-method (op (b1 <bytevector>) (a2 <py-bytearray>))
     (let ((b2 (slot-ref a2 'vec))
	   (n2 (slot-ref a2 'n)))
       (cmp op b1 (b-len b1) b2 n2)))
   (define-method (op (a1 <py-bytearray>) (s2 <py-bytes>))
     (let ((b1 (slot-ref a1 'vec))
	   (n1 (slot-ref a1 'n))
	   (b2 (slot-ref s2 'bytes)))
       (cmp op b1 n1 b2 (b-len b2))))
   (define-method (op (s1 <py-bytes>) (a2 <py-bytearray>))
     (let ((b2 (slot-ref a2 'vec))
	   (n2 (slot-ref a2 'n))
	   (b1 (slot-ref s1 'bytes)))
       (cmp op b1 (b-len b1) b2 n2)))
   (define-method (op (a1 <py-bytearray>) (a2 <py-bytearray>))
     (let ((b1 (slot-ref a1 'vec))
	   (n1 (slot-ref a1 'n  ))
	   (b2 (slot-ref a2 'vec))
	   (n2 (slot-ref a2 'n  )))
       (cmp op b1 n1 b2 n2)))))
   
(mkop <)
(mkop <=)
(mkop >)
(mkop >=)
(mkop py-equal?)

(define-py* zfill (py-zfill bytes s n width)
  (let* ((w (pylist-slice s 0 n 1)))
    (let lp ((i 0))
      (if (< i n)
          (let* ((x  (b-ref s i))
                 (ch (chf x)))
            (if (char-numeric? ch)
                (let lp ((j (max 0 (- i width))))
                  (if (< j i)
                      (begin
                        (b-set! w j (ch-find #\0))
                        (lp (+ j 1)))
                      (bytes w)))
                (lp (+ i 1))))
          s))))

  (define-method (py-hash (o <py-bytes>)) (hash (slot-ref o 'bytes) pyhash-N))

(define-class <bytes-iter>     (<py-bytes>)     i d)
(define-class <bytearray-iter> (<py-bytearray>) i d)

(define-method (wrap-in (o <bytes-iter> ))
  (let ((out (make <bytes-iter>)))
    (slot-set! out 'bytes (slot-ref o 'bytes))
    (slot-set! out 'i   (slot-ref o 'i))
    (slot-set! out 'd   (slot-ref o 'd))
    out))

(define-method (wrap-in (o <bytearray-iter> ))
  (let ((out (make <bytearray-iter>)))
    (slot-set! out 'vec (slot-ref o 'vec))
    (slot-set! out 'n   (slot-ref o 'n))
    (slot-set! out 'i   (slot-ref o 'i))
    (slot-set! out 'd   (slot-ref o 'd))
    out))

(define-method (wrap-in (s <bytevector>))
  (let ((out (make <bytes-iter>)))
    (slot-set! out 'bytes s)
    (slot-set! out 'i   0)
    (slot-set! out 'd   1)
    out))

(define-method (wrap-in (s <py-bytes>))
  (let ((out (make <bytes-iter>)))
    (slot-set! out 'bytes (slot-ref s 'bytes))
    (slot-set! out 'i   0)
    (slot-set! out 'd   1)
    out))

(define-method (wrap-in (s <py-bytearray>))
  (let ((out (make <bytes-iter>)))
    (slot-set! out 'vec (slot-ref s 'vec))
    (slot-set! out 'n   (slot-ref s 'n))
    (slot-set! out 'i   0)
    (slot-set! out 'd   1)
    out))

(define-method (py-reversed (s <py-bytes>))
  (let ((out (make <bytes-iter>)))
    (slot-set! out 'bytes (slot-ref s 'bytes))
    (slot-set! out 'i   (- (b-len s) 1))
    (slot-set! out 'd   -1)
    out))

(define-method (py-reversed (s <py-bytearray>))
  (let ((out (make <bytearray-iter>)))
    (slot-set! out 'n   (slot-ref s 'n))
    (slot-set! out 'vec (slot-ref s 'vec))
    (slot-set! out 'i   (- (slot-ref s 'n) 1))
    (slot-set! out 'd   -1)
    out))

(define-method (next (o <bytes-iter>))
  (let ((i   (slot-ref o 'i  ))
        (d   (slot-ref o 'd))
        (bytes (slot-ref o 'bytes)))
    (if (> d 0)
        (if (< i (b-len bytes))
            (let ((ret (b-ref bytes i)))
              (slot-set! o 'i (+ i d))
              ret)
            (throw StopIteration))
        (if (>= i 0)
            (let ((ret (b-ref bytes i)))
              (slot-set! o 'i (+ i d))
              ret)
            (throw StopIteration)))))

(define-method (next (o <bytearray-iter>))
  (let ((i     (slot-ref o 'i  ))
        (d     (slot-ref o 'd  ))
        (bytes (slot-ref o 'vec))
        (n     (slot-ref o 'n  )))
    (if (> d 0)
        (if (< i n)
            (let ((ret (b-ref bytes i)))
              (slot-set! o 'i (+ i d))
              ret)
            (throw StopIteration))
        (if (>= i 0)
            (let ((ret (b-ref bytes i)))
              (slot-set! o 'i (+ i d))
              ret)
            (throw StopIteration)))))

(define (pybytes-listing)
  (let ((l (to-pylist
            (map symbol->string
                 '(__add__ __class__ __contains__ __delattr__ __doc__
                           __eq__ __format__ __ge__ __getattribute__
                           __getitem__ __getnewargs__ __getslice__ __gt__
                           __hash__ __init__ __le__ __len__ __lt__ __mod__
                           __mul__ __ne__ __new__ __reduce__ __reduce_ex__
                           __repr__ __rmod__ __rmul__ __setattr__ __sizeof__
                           __bytes__ __subclasshook__
                           _formatter_field_name_split _formatter_parser
                           capitalize center count decode endswith
                           expandtabs find format index isalnum isalpha
                           isdigit islower isspace istitle isupper join
                           ljust lower lbytesip partition replace rfind rindex
                           rjust rpartition rsplit rbytesip split splitlines
                           startswith strip swapcase
                           title translate upper zfill)))))
     (pylist-sort! l)
    l))

(define (pybytesarray-listing)
  (let ((l (to-pylist
            (map symbol->string
		 '(__add__  __alloc__ __class__ __contains__ __delattr__
			    __delitem__ __dir__ __doc__ __eq__ __format__
			    __ge__ __getattribute__ __getitem__ __gt__
			    __hash__ __iadd__ __imul__ __init__ __iter__
			    __le__ __len__ __lt__ __mod__ __mul__ __ne__
			    __new__ __reduce__ __reduce_ex__ __repr__
			    __rmod__ __rmul__ __setattr__ __setitem__
			    __sizeof__ __str__ __subclasshook__ append
			    capitalize center clear copy count decode endswith
			    expandtabs extend find fromhex hex index insert
			    isalnum isalpha isdigit islower isspace istitle
			    isupper join ljust lower lstrip maketrans
			    partition pop remove replace reverse rfind rindex
			    rjust rpartition rsplit rstrip split splitlines
			    startswith strip swapcase title translate upper
			    zfill)))))
    (pylist-sort! l)
    l))

(define (_in x y n)
  (let lp ((i 0))
    (if (< i n)
        (if (= (b-ref y i) x)
            #t
            (lp (+ i 1)))
        #f)))

(define (_in2 x y n)
  (let lp ((i 0))
    (if (< i n)
        (let lp2 ((j i) (r x))
          (if (null? r)
              #t
              (if (< j n)
                  (if (= (b-ref y j) (car r))
                      (lp2 (+ j 1) (cdr r))
                      (lp (+ i 1)))
                  #f)))
        #f)))

(define-method (in (x <integer>) (b <bytevector>))
  (_in x b (len b)))
(define-method (in (x <integer>) (b <py-bytes>))
  (_in x (slot-ref b 'bytes) (len b)))
(define-method (in (x <integer>) (b <py-bytearray>))
  (_in x (slot-ref b 'vec) (len b)))

(define-method (in (x <pair>) (b <bytevector>))
  (_in2 x b (len b)))
(define-method (in (x <pair>) (b <py-bytes>))
  (_in2 x (slot-ref b 'bytes) (len b)))
(define-method (in (x <pair>) (b <py-bytearray>))
  (_in2 x (slot-ref b 'vec) (len b)))

(define-method (in (x <bytevector>) b)
  (in (b->list x) b))
(define-method (in (x <py-bytes>) b)
  (in (b->list x) b))
(define-method (in (x <py-bytearray>) b)
  (in (b->list x) b))


(set! (@@ (language python string) bytes) bytes)
(set! (@@ (language python string) b?)
  (lambda (x)
    (or (is-a? x <bytevector>)
        (is-a? x <py-bytes>)
        (is-a? x <py-bytearray>))))
(set! (@@ (language python string) b-decode) py-decode)

(define b-enc   #f)