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

import java.net.URI

// based on 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
  }

  def interpolate(sc: StringContext, args: String*): URI = {
    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())
    }
    new URI(sb.toString)
  }
}