-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path037-libraries-in-solidity.sol
99 lines (86 loc) · 2.38 KB
/
037-libraries-in-solidity.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
/**
* @title Libraries In Solidity
* @notice Libraries are similar to Contracts but are mainly intended for reuse.
* A Library contains functions which other contracts can call.
* Solidity have certain restrictions on use of a Library.
*
* Following are the key characteristics of a Solidity Library.
*
* 1. Library functions can be called directly if they do not modify the state.
* That means pure or view functions only can be called from outside the library.
*
* 2. Library can not be destroyed as it is assumed to be stateless.
*
* 3. A Library cannot have state variables.
*
* 4. A Library cannot inherit any element.
*
* 5. A Library cannot be inherited.
*/
library SearchLibrary {
function indexOf(uint256[] storage self, uint256 value)
public
view
returns (uint256)
{
for (uint256 i = 0; i < self.length; i++) {
if (self[i] == value) return i;
}
// not practical
// this is just so we do not get a warning first
return 0;
}
}
contract LibraryTest {
uint256[] data;
// instantiating our state
constructor() {
data.push(0);
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
// check if given value is present within the array
function isValuePresent(uint256 val) external view returns (uint256) {
uint256 value = val;
uint256 index = SearchLibrary.indexOf(data, value);
return index;
}
}
// Exercise
library SearchLibrary2 {
function indexOf(uint256[] storage self, uint256 value)
public
view
returns (uint256)
{
for (uint256 i = 0; i < self.length; i++) {
if (self[i] == value) return i;
}
// not practical
// this is just so we do not get a warning first
return 0;
}
}
contract LibraryTest2 {
using SearchLibrary2 for uint256[];
uint256[] data;
// instantiating our state
constructor() {
data.push(0);
data.push(1);
data.push(2);
data.push(3);
data.push(4);
data.push(5);
}
// check if given value is present within the array
function isValuePresent() external view returns (uint256) {
uint256 index = data.indexOf(4);
return index;
}
}