Usermode/ld-acess - Clean up loadlib.c, improved debug
[tpg/acess2.git] / KernelLand / 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 = calloc(1, sizeof(tRingBuffer)+Space);
16         ret->Space = Space;
17         return ret;
18 }
19
20 void RingBuffer_Free(tRingBuffer *Buffer)
21 {
22         free(Buffer);
23 }
24
25 size_t RingBuffer_Read(void *Dest, tRingBuffer *Buffer, size_t Length)
26 {
27         size_t  tmpLen;
28
29         tmpLen = Buffer->Length;        // Changed in Write, so cache it for our read
30
31         if(Length > tmpLen)     Length = tmpLen;
32         
33         if( Buffer->Start + Length > Buffer->Space )
34         {
35                  int    endData = Buffer->Space - Buffer->Start;
36                 memcpy(Dest, &Buffer->Data[Buffer->Start], endData);
37                 memcpy((Uint8*)Dest + endData, Buffer->Data, Length - endData);
38         }
39         else
40         {
41                 memcpy(Dest, &Buffer->Data[Buffer->Start], Length);
42         }
43
44         // Lock then modify
45         SHORTLOCK( &Buffer->Lock );
46         Buffer->Start += Length;
47         if( Buffer->Start > Buffer->Space )
48                 Buffer->Start -= Buffer->Space;
49         Buffer->Length -= Length;
50         SHORTREL( &Buffer->Lock );
51
52         return Length;
53 }
54
55 size_t RingBuffer_Write(tRingBuffer *Buffer, const void *Source, size_t Length)
56 {
57         size_t  bufEnd, endSpace;
58         size_t  tmpLen, tmpStart;
59         
60         // Cache Start and Length because _Read can change these
61         SHORTLOCK( &Buffer->Lock );
62         tmpStart = Buffer->Start;
63         tmpLen = Buffer->Length;
64         SHORTREL( &Buffer->Lock );
65
66         bufEnd = (tmpStart + Buffer->Length) % Buffer->Space;
67         endSpace = Buffer->Space - bufEnd;
68         
69         // Force to bounds
70         if(Length > Buffer->Space - tmpLen)     Length = Buffer->Space - tmpLen;
71         
72         if(endSpace < Length)
73         {
74                 memcpy( &Buffer->Data[bufEnd], Source, endSpace );
75                 memcpy( Buffer->Data, (Uint8*)Source + endSpace, Length - endSpace );
76         }
77         else
78         {
79                 memcpy( &Buffer->Data[bufEnd], Source, Length );
80         }
81
82         // Lock then modify
83         SHORTLOCK( &Buffer->Lock );
84         Buffer->Length += Length;
85         SHORTREL( &Buffer->Lock );
86         
87         return Length;
88 }
89

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