1 // Written in the D programming language.
2 
3 /**
4 A type for representing the perm object of the 9P / Styx protocol. 
5 
6 Copyright: LightHouse Software, 2021
7 License:   $(HTTP https://github.com/aquaratixc/ESL-License, Experimental Software License 1.0).
8 Authors:   Oleg Bakharev,
9 		   Ilya Pertsev
10 */
11 module styx2000.protobj.perm;
12 
13 private {
14 	import std..string : format;
15 	
16 	import styx2000.lowlevel.endianness;
17 	
18 	import styx2000.protobj.styxobject;
19 }
20 
21 public {
22 	import styx2000.protoconst.permissions;
23 }
24 
25 /**
26 	A class that provides a type for the perm field in some Styx messages. Inherits methods from StyxObject class. 
27 	See_Also:
28 		https://web.archive.org/web/20201029184954/https://powerman.name/Inferno/man/5/0intro.html
29 */
30 class Perm : StyxObject
31 {
32 	protected {
33 		uint _perm;
34 		
35 		ubyte[] _representation;
36 	}
37 	
38 	/**
39 	A constructor that creates an object of the Perm class with the given parameter in the form of unsigned value. 
40 	If called without parameters, then the default parameter is zero.
41 	Params:
42     perm = Permissions as unsigned value.
43     
44     Typical usage:
45     ----
46     Perm perm = new Perm(0x0000);
47     ----
48     */
49 	this(uint perm = 0)
50 	{
51 		_perm = perm;
52 		_representation = toLEBytes!uint(perm);
53 	}
54 	
55 	/// Get value from Perm object as unsigned value
56 	uint getPerm()
57 	{
58 		return _perm;
59 	}
60 	
61 	/// Set Perm object from unsigned value
62 	void setPerm(uint perm)
63 	{
64 		_perm = perm;
65 		_representation = toLEBytes!uint(perm);
66 	}
67 	
68 	/// Set Perm object from STYX_FILE_PERMISSION list
69 	void setPerm(STYX_FILE_PERMISSION[] perm...)
70 	{
71 		uint permissions;
72 		
73 		foreach (e; perm)
74 		{
75 			permissions |= cast(uint) e;
76 		}
77 		_perm = permissions;
78 		_representation = toLEBytes!uint(permissions);
79 	}
80 	
81 	/// Pack to bytes array
82 	ubyte[] pack()
83 	{
84 		return _representation;
85 	}
86 	
87 	/// Unpack from bytes array
88 	void unpack(ubyte[] bytes...)
89 	{
90 		_representation = bytes[0..4];
91 		_perm = fromLEBytes!uint(bytes[0..4]);
92 	}
93 	
94 	/// Convenient string representation of an object for printing 
95 	override string toString()
96 	{
97 		return format(`Permissions(perm=0x%0.8x)`, _perm);
98 	}
99 	
100 	/// An alias for easier packing into a byte array without having to manually call the pack() method
101 	alias pack this;
102 }