xref: /haiku/src/kits/mail/NodeMessage.cpp (revision d3d8b26997fac34a84981e6d2b649521de2cc45a)
1 #include "NodeMessage.h"
2 #include <StorageKit.h>
3 #include <fs_attr.h>
4 #include <stdlib.h>
5 
6 /*
7    These functions gives a nice BMessage interface to node attributes,
8    by letting you transfer attributes to and from BMessages.  It makes
9    it so you can use all the convenient Find...() and Add...() functions
10    provided by BMessage for attributes too.  You use it as follows:
11 
12    BMessage m;
13    BNode n(path);
14    if (reading) { n>>m; printf("woohoo=%s\n",m.FindString("woohoo")) }
15    else { m.AddString("woohoo","it's howdy doody time"); n<<m; }
16 
17    If there is more than one data item with a given name, the first
18    item is the one writen to the node.
19 */
20 _EXPORT BNode& operator<<(BNode& n, const BMessage& m)
21 {
22 	#if defined(HAIKU_TARGET_PLATFORM_DANO)
23 	const
24 	#endif
25 	char *name;
26 	type_code   type;
27 	ssize_t     bytes;
28 	const void *data;
29 
30 	for(int32 i = 0;
31 		m.GetInfo(B_ANY_TYPE, i, &name, &type) == 0;
32 		i++)
33 	{
34 		m.FindData (name,type,0,&data,&bytes);
35 		n.WriteAttr(name,type,0, data, bytes);
36 	}
37 
38 	return n;
39 }
40 
41 _EXPORT BNode& operator>>(BNode& n, BMessage& m)
42 {
43 	char        name[B_ATTR_NAME_LENGTH];
44 	attr_info	info;
45 	char *buf = NULL;
46 
47 	n.RewindAttrs();
48 	while (n.GetNextAttrName(name)==B_OK)
49 	{
50 		if (n.GetAttrInfo(name,&info) != B_OK)
51 			continue;
52 
53 		// resize the buffer
54 		if (char *newBuffer = (char*)realloc(buf, info.size))
55 			buf = newBuffer;
56 		else
57 			continue;
58 
59 		info.size=n.ReadAttr(name,info.type,0,buf,info.size);
60 		if (info.size >= 0)
61 			m.AddData(name,info.type,buf,info.size);
62 	}
63 	n.RewindAttrs();
64 
65 	free(buf);
66 
67 	return n;
68 }
69