Kernel - Misc minor fixes
[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 size_t RingBuffer_Read(void *Dest, tRingBuffer *Buffer, size_t Length)
21 {
22         size_t  tmpLen;
23
24         tmpLen = Buffer->Length;        // Changed in Write, so cache it for our read
25
26         if(Length > tmpLen)     Length = tmpLen;
27         
28         if( Buffer->Start + Length > Buffer->Space )
29         {
30                  int    endData = Buffer->Space - Buffer->Start;
31                 memcpy(Dest, &Buffer->Data[Buffer->Start], endData);
32                 memcpy((Uint8*)Dest + endData, Buffer->Data, Length - endData);
33         }
34         else
35         {
36                 memcpy(Dest, &Buffer->Data[Buffer->Start], Length);
37         }
38
39         // Lock then modify
40         SHORTLOCK( &Buffer->Lock );
41         Buffer->Start += Length;
42         if( Buffer->Start > Buffer->Space )
43                 Buffer->Start -= Buffer->Space;
44         Buffer->Length -= Length;
45         SHORTREL( &Buffer->Lock );
46
47         return Length;
48 }
49
50 size_t RingBuffer_Write(tRingBuffer *Buffer, const void *Source, size_t Length)
51 {
52         size_t  bufEnd, endSpace;
53         size_t  tmpLen, tmpStart;
54         
55         // Cache Start and Length because _Read can change these
56         SHORTLOCK( &Buffer->Lock );
57         tmpStart = Buffer->Start;
58         tmpLen = Buffer->Length;
59         SHORTREL( &Buffer->Lock );
60
61         bufEnd = (tmpStart + Buffer->Length) % Buffer->Space;
62         endSpace = Buffer->Space - bufEnd;
63         
64         // Force to bounds
65         if(Length > Buffer->Space - tmpLen)     Length = Buffer->Space - tmpLen;
66         
67         if(endSpace < Length)
68         {
69                 memcpy( &Buffer->Data[bufEnd], Source, endSpace );
70                 memcpy( Buffer->Data, (Uint8*)Source + endSpace, Length - endSpace );
71         }
72         else
73         {
74                 memcpy( &Buffer->Data[bufEnd], Source, Length );
75         }
76
77         // Lock then modify
78         SHORTLOCK( &Buffer->Lock );
79         Buffer->Length += Length;
80         SHORTREL( &Buffer->Lock );
81         
82         return Length;
83 }
84

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