1 // Written in the D programming language.
2 
3 /**
4 A type for representing the offset 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.offset;
12 
13 private {
14 	import std..string : format;
15 	
16 	import styx2000.lowlevel.endianness;
17 	
18 	import styx2000.protobj.styxobject;
19 }
20 
21 /**
22 	A class that provides a type for the offset field in some Styx messages. Inherits methods from StyxObject class. 
23 	See_Also:
24 		https://web.archive.org/web/20201029184954/https://powerman.name/Inferno/man/5/0intro.html
25 */
26 class Offset : StyxObject
27 {
28 	protected {
29 		ulong _offset;
30 		
31 		ubyte[] _representation;
32 	}
33 	
34 	/**
35 	A constructor that creates an object of the Offset class with the given parameter in the form of unsigned value. 
36 	If called without parameters, then the default parameter is zero.
37 	Params:
38     size = Number of unsigned bytes.
39     
40     Typical usage:
41     ----
42     Offset offset = new Offset(1);
43     ----
44     */
45 	this(ulong offset = 0)
46 	{
47 		_offset = offset;
48 		_representation = toLEBytes!ulong(offset);
49 	}
50 	
51 	/// Get offset from Offset object
52 	ulong getOffset()
53 	{
54 		return _offset;
55 	}
56 	
57 	/// Set offset from unsigned value
58 	void setOffset(ulong offset)
59 	{
60 		_offset = offset;
61 		_representation = toLEBytes!ulong(offset);
62 	}
63 	
64 	/// Pack to bytes array
65 	ubyte[] pack()
66 	{
67 		return _representation;
68 	}
69 	
70 	/// Unpack from bytes array
71 	void unpack(ubyte[] bytes...)
72 	{
73 		_representation = bytes[0..8];
74 		_offset = fromLEBytes!ulong(bytes[0..8]);
75 	}
76 	
77 	/// Convenient string representation of an object for printing 
78 	override string toString()
79 	{
80 		return format(`Offset(offset=%d)`, _offset);
81 	}
82 	
83 	/// An alias for easier packing into a byte array without having to manually call the pack() method
84 	alias pack this;
85 }