1 /*
2  * Copyright (c) 1988, 1989, 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Adam de Boor.
7  *
8  * Redistribution and use in source and binary forms are permitted
9  * provided that the above copyright notice and this paragraph are
10  * duplicated in all such forms and that any documentation,
11  * advertising materials, and other materials related to such
12  * distribution and use acknowledge that the software was developed
13  * by the University of California, Berkeley.  The name of the
14  * University may not be used to endorse or promote products derived
15  * from this software without specific prior written permission.
16  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19  */
20 
21 #ifndef lint
22 static char sccsid[] = "@(#)lstInsert.c	5.2 (Berkeley) 03/11/90";
23 #endif /* not lint */
24 
25 /*-
26  * LstInsert.c --
27  *	Insert a new datum before an old one
28  */
29 
30 #include	"lstInt.h"
31 
32 /*-
33  *-----------------------------------------------------------------------
34  * Lst_Insert --
35  *	Insert a new node with the given piece of data before the given
36  *	node in the given list.
37  *
38  * Results:
39  *	SUCCESS or FAILURE.
40  *
41  * Side Effects:
42  *	the firstPtr field will be changed if ln is the first node in the
43  *	list.
44  *
45  *-----------------------------------------------------------------------
46  */
47 ReturnStatus
48 Lst_Insert (l, ln, d)
49     Lst	    	  	l;	/* list to manipulate */
50     LstNode	  	ln;	/* node before which to insert d */
51     ClientData	  	d;	/* datum to be inserted */
52 {
53     register ListNode	nLNode;	/* new lnode for d */
54     register ListNode	lNode = (ListNode)ln;
55     register List 	list = (List)l;
56 
57 
58     /*
59      * check validity of arguments
60      */
61     if (LstValid (l) && (LstIsEmpty (l) && ln == NILLNODE))
62 	goto ok;
63 
64     if (!LstValid (l) || LstIsEmpty (l) || !LstNodeValid (ln, l)) {
65 	return (FAILURE);
66     }
67 
68     ok:
69     PAlloc (nLNode, ListNode);
70 
71     nLNode->datum = d;
72     nLNode->useCount = nLNode->flags = 0;
73 
74     if (ln == NILLNODE) {
75 	if (list->isCirc) {
76 	    nLNode->prevPtr = nLNode->nextPtr = nLNode;
77 	} else {
78 	    nLNode->prevPtr = nLNode->nextPtr = NilListNode;
79 	}
80 	list->firstPtr = list->lastPtr = nLNode;
81     } else {
82 	nLNode->prevPtr = lNode->prevPtr;
83 	nLNode->nextPtr = lNode;
84 
85 	if (nLNode->prevPtr != NilListNode) {
86 	    nLNode->prevPtr->nextPtr = nLNode;
87 	}
88 	lNode->prevPtr = nLNode;
89 
90 	if (lNode == list->firstPtr) {
91 	    list->firstPtr = nLNode;
92 	}
93     }
94 
95     return (SUCCESS);
96 }
97 
98