RandomRow.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright IBM Corporation 2018
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Foundation
  17. // Return a random number within the range of rows in the database
  18. private func randomNumberGenerator(_ maxVal: Int) -> Int {
  19. #if os(Linux)
  20. return Int(random() % maxVal) + 1
  21. #else
  22. return Int(arc4random_uniform(UInt32(maxVal))) + 1
  23. #endif
  24. }
  25. public struct RandomRow: Codable {
  26. /// The number of rows in the World table
  27. public static let dbRows = 10000
  28. /// The maximum value for randomNumber
  29. public static let maxValue = 10000
  30. /// A generated random row id suitable for retrieving
  31. /// or creating a RandomRow instance.
  32. public static var randomId: Int {
  33. return randomNumberGenerator(dbRows)
  34. }
  35. /// A generated random value suitable for assigning as the
  36. /// `randomNumber` for a RandomRow instance.
  37. public static var randomValue: Int {
  38. return randomNumberGenerator(maxValue)
  39. }
  40. /// The id for this RandomRow, ranging from 1 to dbRows
  41. public let id: Int
  42. /// A random number ranging from 1 to maxValue
  43. public let randomNumber: Int
  44. public init(id: Int, randomNumber: Int) {
  45. self.id = id
  46. self.randomNumber = randomNumber
  47. }
  48. /// Map the properties of this type to their corresponding database
  49. /// column names (required by the ORM).
  50. enum CodingKeys: String, CodingKey {
  51. case id
  52. case randomNumber = "randomnumber"
  53. }
  54. /// Returns a JSON-convertible dictionary representation of this RandomRow.
  55. public func asDictionary() -> [String: Int] {
  56. return ["id": self.id, "randomNumber": self.randomNumber]
  57. }
  58. }