1 /* 2 * hunt-proton: AMQP Protocol library for D programming language. 3 * 4 * Copyright (C) 2018-2019 HuntLabs 5 * 6 * Website: https://www.huntlabs.net/ 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module hunt.proton.codec.impl.IntegerElement; 13 14 import hunt.io.ByteBuffer; 15 import std.conv; 16 import hunt.proton.codec.impl.AtomicElement; 17 import hunt.proton.codec.impl.Element; 18 import hunt.proton.codec.impl.ArrayElement; 19 import hunt.proton.codec.impl.AbstractElement; 20 import hunt.Integer; 21 22 import hunt.proton.codec.Data; 23 24 class IntegerElement : AtomicElement!Integer 25 { 26 27 private int _value; 28 29 this(IElement parent,IElement prev, int i) 30 { 31 super(parent, prev); 32 _value = i; 33 } 34 35 public int size() 36 { 37 if(isElementOfArray()) 38 { 39 ArrayElement parent = cast(ArrayElement) parent(); 40 if(parent.constructorType() == ArrayElement.SMALL) 41 { 42 if(-128 <= _value && _value <= 127) 43 { 44 return 1; 45 } 46 else 47 { 48 parent.setConstructorType(ArrayElement.LARGE); 49 return 4; 50 } 51 } 52 else 53 { 54 return 4; 55 } 56 } 57 else 58 { 59 return (-128 <= _value && _value <= 127) ? 2 : 5; 60 } 61 62 } 63 64 public Object getValue() 65 { 66 return new Integer( _value); 67 } 68 69 public Data.DataType getDataType() 70 { 71 return Data.DataType.INT; 72 } 73 74 public int encode(ByteBuffer b) 75 { 76 int size = size(); 77 if(size <= b.remaining()) 78 { 79 switch(size) 80 { 81 case 2: 82 { 83 b.put(cast(byte)0x54); 84 goto case; 85 } 86 case 1: 87 { 88 b.put(cast(byte)_value); 89 break; 90 } 91 92 case 5: 93 { 94 b.put(cast(byte)0x71); 95 goto case; 96 } 97 98 case 4: 99 { 100 b.putInt(_value); 101 break; 102 } 103 104 default: 105 break; 106 } 107 108 return size; 109 } 110 return 0; 111 } 112 }