Usermode/ld-acess - Disabled PIC (not needed)
[tpg/acess2.git] / Kernel / adt.c
1 /*
2  * Acess2 Kernel
3  * 
4  * adt.c
5  * - Complex data type code
6  */
7 #include <acess.h>
8 #include <adt.h>
9
10
11 // === CODE ===
12 // --- Ring Buffers ---
13 tRingBuffer *RingBuffer_Create(size_t Space)
14 {
15         tRingBuffer     *ret = malloc(sizeof(tRingBuffer)+Space);
16         ret->Start = 0;
17         ret->Length = 0;
18         ret->Space = Space;
19         return ret;
20 }
21
22 size_t RingBuffer_Read(void *Dest, tRingBuffer *Buffer, size_t Length)
23 {
24         size_t  tmpLen;
25
26         tmpLen = Buffer->Length;        // Changed in Write, so cache it for our read
27
28         if(Length > tmpLen)     Length = tmpLen;
29         
30         if( Buffer->Start + Length > Buffer->Space )
31         {
32                  int    endData = Buffer->Space - Buffer->Start;
33                 memcpy(Dest, &Buffer->Data[Buffer->Start], endData);
34                 memcpy((Uint8*)Dest + endData, Buffer->Data, Length - endData);
35         }
36         else
37         {
38                 memcpy(Dest, &Buffer->Data[Buffer->Start], Length);
39         }
40
41         // Lock then modify
42         SHORTLOCK( &Buffer->Lock );
43         Buffer->Start += Length;
44         if( Buffer->Start > Buffer->Space )
45                 Buffer->Start -= Buffer->Space;
46         Buffer->Length -= Length;
47         SHORTREL( &Buffer->Lock );
48
49         return Length;
50 }
51
52 size_t RingBuffer_Write(tRingBuffer *Buffer, const void *Source, size_t Length)
53 {
54         size_t  bufEnd, endSpace;
55         size_t  tmpLen, tmpStart;
56         
57         // Cache Start and Length because _Read can change these
58         SHORTLOCK( &Buffer->Lock );
59         tmpStart = Buffer->Start;
60         tmpLen = Buffer->Length;
61         SHORTREL( &Buffer->Lock );
62
63         bufEnd = (tmpStart + Buffer->Length) % Buffer->Space;
64         endSpace = Buffer->Space - bufEnd;
65         
66         // Force to bounds
67         if(Length > Buffer->Space - tmpLen)     Length = Buffer->Space - tmpLen;
68         
69         if(endSpace < Length)
70         {
71                 memcpy( &Buffer->Data[bufEnd], Source, endSpace );
72                 memcpy( Buffer->Data, (Uint8*)Source + endSpace, Length - endSpace );
73         }
74         else
75         {
76                 memcpy( &Buffer->Data[bufEnd], Source, Length );
77         }
78
79         // Lock then modify
80         SHORTLOCK( &Buffer->Lock );
81         Buffer->Length += Length;
82         SHORTREL( &Buffer->Lock );
83         
84         return Length;
85 }
86

UCC git Repository :: git.ucc.asn.au