]> git.sur5r.net Git - cc65/blob - libsrc/common/strncpy.s
Fixed a bug
[cc65] / libsrc / common / strncpy.s
1 ;
2 ; Ullrich von Bassewitz, 31.05.1998
3 ;
4 ; char* strncpy (char* dest, const char* src, unsigned size);
5 ;
6
7         .export         _strncpy
8         .import         popax
9         .importzp       ptr1, ptr2, ptr3, tmp1, tmp2
10
11 _strncpy:
12         sta     tmp1            ; Save size
13         stx     tmp2
14         jsr     popax           ; get src
15         sta     ptr1
16         stx     ptr1+1
17         jsr     popax           ; get dest
18         sta     ptr2
19         stx     ptr2+1
20         sta     ptr3            ; remember for function return
21         stx     ptr3+1
22
23         ldy     #$00
24         ldx     tmp1            ; Low byte of size
25         beq     L1
26
27 ; Copy the first chunk < 256
28
29         jsr     CopyChunk
30         bcs     L3              ; Jump if end of string found
31
32 ; Copy full 256 byte chunks
33
34 L1:     lda     tmp2            ; High byte of size
35         beq     L3
36         ldx     #$00            ; Copy 256 bytes
37 L2:     jsr     CopyChunk
38         bcs     L3
39         dec     tmp2
40         bne     L2
41         beq     L9
42
43 ; Fill the remaining space with zeroes. If we come here, the value in X
44 ; is the low byte of the fill count, tmp2 holds the high byte. Y is the index
45 ; into the target string.
46
47 L3:     tax                     ; Test low byte
48         beq     L4
49         jsr     FillChunk
50
51 L4:     lda     tmp2            ; Test high byte
52         beq     L9
53 L5:     jsr     FillChunk
54         dec     tmp2
55         bne     L5
56
57 ; Done - return a pointer to the string
58
59 L9:     lda     ptr3
60         ldx     ptr3+1
61         rts
62
63
64 ; -------------------------------------------------------------------
65 ; Copy byte count in X from ptr1 to ptr2
66
67 .proc   CopyChunk
68 L1:     lda     (ptr1),y
69         sta     (ptr2),y
70         beq     L3
71         iny
72         bne     L2
73         inc     ptr1+1
74         inc     ptr2+1
75 L2:     dex
76         bne     L1
77         clc
78         rts
79 L3:     sec
80         rts
81 .endproc
82
83
84 ; -------------------------------------------------------------------
85 ; Fill byte count in X with zeroes
86
87 .proc   FillChunk
88         lda     #$00
89 L1:     sta     (ptr1),y
90         iny
91         bne     L2
92         inc     ptr1+1
93 L2:     dex
94         bne     L1
95         rts
96 .endproc
97
98