aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/scala/com/softwaremill/sttp/UriInterpolator.scala
blob: abb23276e17bc4c6cf45487a5e33e7104ea8d26e (plain) (blame)
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
package com.softwaremill.sttp

// from https://gist.github.com/teigen/5865923
object UriInterpolator {

  private val unreserved = {
    val alphanum = (('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')).toSet
    val mark     = Set('-', '_', '.', '!', '~', '*', '\'', '(', ')')
    alphanum ++ mark
  }

  implicit class UriContext(val sc:StringContext) extends AnyVal {
    def uri(args:String*) = {
      val strings     = sc.parts.iterator
      val expressions = args.iterator
      val sb          = new StringBuffer(strings.next())

      while(strings.hasNext){
        for(c <- expressions.next()){
          if(unreserved(c))
            sb.append(c)
          else for(b <- c.toString.getBytes("UTF-8")){
            sb.append("%")
            sb.append("%02X".format(b))
          }
        }
        sb.append(strings.next())
      }
      sb.toString
    }
  }
}